28

Is there any way to check that a variable is a valid JSON string in PHP without using json_last_error()? My PHP version is older than 5.3.0.

3
  • What version of PHP do you have? Commented Oct 20, 2011 at 20:14
  • You could still test if a valid value comes out of just decoding it, even if you won't know the exact syntax error. (Or use a regex to validate it. ha) Commented Oct 20, 2011 at 20:17
  • json_decode will return null on failure, and it's available on PHP >= 5.2. Commented Oct 20, 2011 at 20:17

5 Answers 5

65
$ob = json_decode($json);
if($ob === null) {
 // $ob is null because the json cannot be decoded
}
Sign up to request clarification or add additional context in comments.

14 Comments

Fails if the json string is a simple (valid) 'false' value.
Unfortunately this isn't a true validation. It is still possible to send invalid json but json_decode() will interpret it, but not in the way you'd expect. This is considered valid json: {"request": { "filterBy": "MCC" "startDate": "Sun, 02 Sep 2012 12:51:44 -0400", "endDate": "Tue, 02 Oct 2012 00:00:00 -0400" }} even though there's a missing comma after "MCC"
@Webnet tested at jsonlint.com and your string did not validate. Can you point to a specification or tool that says your string is valid?
It can go both ways too. There are some control characters, such as an ASCII 26, which, when present in json, will cause json_decode() to always fail even though if you parse the same string with javascript, it'll succeed. Which of those is the desirable behavior depends on your application.
@Tayyab_Hussain Your invalid case passes because PHP implements a superset of JSON specified in RFC 7159 vs 'classic' JSON as specified in RFC 4627. See the top note on the manual page. RFC7159 allows simple scalar values not wrapped in an array or object and therefore is 'valid JSON'. See also this question
|
14
$data = json_decode($json_string);
if (is_null($data)) {
   die("Something dun gone blowed up!");
}

1 Comment

You get an updoot just for adding humor and teaching me a new function: is_null.
10

If you want to check if your input is valid JSON, you might as well be interested in validating whether or not it follows a specific format, i.e a schema. In this case you can define your schema using JSON Schema and validate it using this library.

Example:

person.json

{
    "title": "Person",
    "type": "object",
    "properties": {
        "firstName": {
            "type": "string"
        },
        "lastName": {
            "type": "string"
        },
        "age": {
            "description": "Age in years",
            "type": "integer",
            "minimum": 0
        }
    },
    "required": ["firstName", "lastName"]
}

Validation

<?php

$data = '{"firstName":"Hermeto","lastName":"Pascoal"}';

$validator = new JsonSchema\Validator;
$validator->validate($data, (object)['$ref' => 'file://' . realpath('person.json')]);

$validator->isValid()

Comments

3

Furthermore you can have a look on http://php.net/manual/en/function.json-last-error-msg.php that contain implementations of the missing function.

One of them is:

if (!function_exists('json_last_error_msg')) {
        function json_last_error_msg() {
            static $ERRORS = array(
                JSON_ERROR_NONE => 'No error',
                JSON_ERROR_DEPTH => 'Maximum stack depth exceeded',
                JSON_ERROR_STATE_MISMATCH => 'State mismatch (invalid or malformed JSON)',
                JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded',
                JSON_ERROR_SYNTAX => 'Syntax error',
                JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded'
            );

            $error = json_last_error();
            return isset($ERRORS[$error]) ? $ERRORS[$error] : 'Unknown error';
        }
    }

(Copied pasted from the site)

Comments

0

You could check if the value from json_decode is null. If so, it's invalid.

2 Comments

i am using the json_decode function and its behaving very strangely. if i send a request like this: api.nblackburn.me/…{}, it works but if i add some valid json it doesnt, any ideas?
Show us the JSOn you're trying to parse.