Skip to content

Instantly share code, notes, and snippets.

@lenivene
Last active May 25, 2016 19:37
Show Gist options
  • Save lenivene/47a6386cf2f0031edf1f3552af10cb80 to your computer and use it in GitHub Desktop.
Save lenivene/47a6386cf2f0031edf1f3552af10cb80 to your computer and use it in GitHub Desktop.
Check if a "JSON" is a valid JSON

Example code

$json_valid = wp_json_error( $json );

if ( ! is_wp_error( $json_valid ) ) {
	print_r( $json_valid ); // Show $json
} else {
	print_r( $json_valid ); // Show Error
}
<?php
function wp_json_error( $json ){
$json_error = false;
$json_decode = json_decode( $json, true );
if ( json_last_error() === JSON_ERROR_NONE ) {
if ( !empty( $json ) ){
$json = $json_decode;
} else {
$json = $json;
}
} else {
$json_error = true;
}
if ( false !== $json_error ) {
return new WP_Error( 'no_json', __( 'Invalid JSON Provided.' ) );
} else {
return $json;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment