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.

hanshenrik
  • 19,904
  • 4
  • 43
  • 89
  • What version of PHP do you have? – Whetstone Oct 20 '11 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) – mario Oct 20 '11 at 20:17
  • `json_decode` will return `null` on failure, and it's available on PHP >= 5.2. – Jon Oct 20 '11 at 20:17
  • possible duplicate of [PHP is_json function?](http://stackoverflow.com/questions/1187576/php-is-json-function) – mario Oct 20 '11 at 20:21
  • Possible duplicate of [How to determine whether a string is valid JSON?](https://stackoverflow.com/questions/1187576/how-to-determine-whether-a-string-is-valid-json) – kenorb Jan 10 '19 at 15:43
  • **See duplicate:** https://stackoverflow.com/questions/6041741/fastest-way-to-check-if-a-string-is-json-in-php – dreftymac Mar 13 '19 at 22:13

5 Answers5

65
$ob = json_decode($json);
if($ob === null) {
 // $ob is null because the json cannot be decoded
}
Jeff Lambert
  • 24,395
  • 4
  • 69
  • 96
  • 1
    Fails if the json string is a simple (valid) 'false' value. – Marc B Oct 20 '11 at 20:17
  • i am using the json_decode function and its behaving very strangely. if i send a request like this: http://api.nblackburn.me/jobtrackr?task=account&action=modify&session=206a2911127c224a5893b8d78a4bf0fc&params={}, it works but if i add some valid json it doesnt, any ideas? –  Oct 20 '11 at 20:53
  • 17
    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" – Ben Oct 04 '12 at 15:04
  • 2
    @Webnet tested at http://jsonlint.com and your string did not validate. Can you point to a specification or tool that says your string is valid? – Jeff Lambert Oct 31 '12 at 22:31
  • @watcher PHP's json_decode() still decodes that string even with a missing comma. It actually makes a guess which turns out to be incorrect – Ben Nov 01 '12 at 15:35
  • 1
    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. – ZorroDeLaArena May 14 '14 at 21:01
  • @Tayyab_Hussain can you add a test case [here](http://sandbox.onlinephpfunctions.com/code/a6eb430dedc8c7d26c269571bab7af7b1bdc4d13) where the validation fails or succeeds incorrectly? They don't have 5.5.9 but 5.5.5 and 5.5.18 are closest – Jeff Lambert Apr 27 '16 at 09:43
  • @JeffLambert [check](http://sandbox.onlinephpfunctions.com/code/e4655b74abb1f69fc17618ba6ec080717b6bcf3d) – Tayyab Hussain Apr 27 '16 at 10:29
  • 1
    @Tayyab_Hussain Your invalid case passes because PHP implements a superset of JSON specified in [RFC 7159](https://www.ietf.org/rfc/rfc7159.txt) vs 'classic' JSON as specified in [RFC 4627](https://www.ietf.org/rfc/rfc4627.txt). See the top note on the [manual](http://php.net/manual/en/function.json-decode.php) page. RFC7159 allows simple scalar values not wrapped in an array or object and therefore is 'valid JSON'. See also [this question](http://stackoverflow.com/q/19569221/697370) – Jeff Lambert Apr 27 '16 at 14:31
  • I also tried not-so-good technique, which balances the brackets { or ( . in case, if your text has any Error or Typo, say "My address(postal} is ..." than it fails the validation. I am improving it now. hopefully it helps.. – moeen-ud-Din Aug 16 '16 at 13:47
  • If your json is exactly the string 'null' it is valid, but you won't be able to tell with this method. In that case you must use `json_last_error()`. – ADJenks Sep 04 '20 at 18:39
  • 1
    @Webnet. No this string is not valid, answer is correct. http://sandbox.onlinephpfunctions.com/code/a863402445a546c089fdbb39c1dc700c4c8e117a – Dmitry Gordienko Jan 13 '21 at 15:21
  • @JuliSmz Can you share what bad-formed JSON is? As mentioned in the comments previously, PHP implements RFC 7159, not RFC 4627. – Jeff Lambert Jun 28 '21 at 16:55
  • You're right, I will delete my comment. I see json_last_error() > 0 as interesting alternative. Thanks. – JuliSmz Jun 28 '21 at 17:04
14
$data = json_decode($json_string);
if (is_null($data)) {
   die("Something dun gone blowed up!");
}
Marc B
  • 356,200
  • 43
  • 426
  • 500
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()
Jefferson Lima
  • 5,186
  • 2
  • 28
  • 28
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)

Dimitrios Desyllas
  • 9,082
  • 15
  • 74
  • 164
0

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

Alex Turpin
  • 46,743
  • 23
  • 113
  • 145
  • i am using the json_decode function and its behaving very strangely. if i send a request like this: http://api.nblackburn.me/jobtrackr?task=account&action=modify&session=206a2911127c224a5893b8d78a4bf0fc&params={}, it works but if i add some valid json it doesnt, any ideas? –  Oct 20 '11 at 20:50
  • Show us the JSOn you're trying to parse. – Alex Turpin Oct 21 '11 at 13:23