PHP `is_json`

// Check for valid JSON string // Usage: `if (is_json($text)) { … }` function is_json($x) { if (!is_string($x) || !trim($x)) return false; return ( // Maybe an empty string, array or object $x === '""' || $x === '[]' || $x === '{}' || // Maybe an encoded JSON string $x[0] === '"' || // Maybe a flat array $x[0] === '[' || // Maybe an associative array strpos($x, '{"') === 0 ) && json_decode($x) !== null && json_last_error() !== JSON_ERROR_NONE; }
Check if string is a valid JSON.

1 Response

I added that because `null` is also a valid JSON. And PHP `json_decode` simply return the string into `null` if it is invalid or broken.

• Values true, false and null are returned as TRUE, FALSE and NULL respectively.
• NULL is returned if the JSON cannot be decoded or if the encoded data is deeper than the recursion limit.

http://php.net/manual/en/function.json-decode.php#refsect1-function.json-decode-returnvalues

Write a comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.