Home > PHP, Snippets of Code > JSON_ERROR_SYNTAX while decoding huge json-encoded array

JSON_ERROR_SYNTAX while decoding huge json-encoded array

It took me a lot of time to eventually find out what was throwing the JSON error known as “JSON_ERROR_SYNTAX”. I was dealing with a huge array, more than 100,000 entries and 2MB in size. The PHP script processing the data always hangs when trying to decode the big array into a PHP variable. Using PHP function json_last_error() I could find out that JSON decoder was throwing the error code 4, meaning there was a syntax error in the json string.

http://php.net/function.json_last_error

Finally I found the array entry that makes JSON go crazy:

{...
,"laptops":"26"
,null:"26"
,"cad":"26"
,...}

NULL. Yes. That’s the culprit. So, bottom line: avoid array null keys at all cost.

Here is the code I used to locate the error:


<?php
	function json_error() {
		switch(json_last_error()) {
			case JSON_ERROR_NONE:
				return '';
			break;
			case JSON_ERROR_DEPTH:
				return 'JSON_ERROR_DEPTH';
			break;
			case JSON_ERROR_STATE_MISMATCH:
				return 'JSON_ERROR_STATE_MISMATCH';
			break;
			case JSON_ERROR_CTRL_CHAR:
				return 'JSON_ERROR_CTRL_CHAR';
			break;
			case JSON_ERROR_SYNTAX:
				return 'JSON_ERROR_SYNTAX';
			break;
			case JSON_ERROR_UTF8:
				return 'JSON_ERROR_UTF8';
			break;
		}

		return 'Unknown Json error' . json_last_error();
	}

$json='{"laptops":"26"
,null:"26"
,"cad":"26"}';
echo "\nstrlen(json) = " . strlen($json);
$dummy = json_decode($json, 1);
if (json_error()) die('Json Error: ' . json_error() . "\n");
?>

Hope this helps …

Advertisements
  1. Paulo Linhares
    2015/06/16 at 5:36 pm

    Already hit head because developers are testing the Json on localhost, file_get_content calling (“meu_json.php”) in this way, when in fact must report all full url, like this:
    http: //localhost/meu_json.php

    It is just another common problem.

  2. 2014/02/21 at 5:13 pm

    Another reason to get null key arrays is using key strings that include weird letters like “ñ” out of your charset. Be careful with that!

  3. 2014/02/21 at 4:41 pm

    I found explode() PHP function might return null key arrays under certain situations. To avoid it, it is better to use something like that preg_split(‘#, #’, $text, -1, PREG_SPLIT_NO_EMPTY); The flag PREG_SPLIT_NO_EMPTY makes the magic.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: