Posts Tagged ‘array’
JSON_ERROR_SYNTAX while decoding huge json-encoded array
2014/02/21
3 comments
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 …
Categories: PHP, Snippets of Code
array, decode, huge, json, JSON_ERROR_SYNTAX, json_last_error, php