First, here is some backgroung : my current company's servers use old versions of PHP (It's not an option to upgrade it) and json functions are not supported. The company made its own framework with a dedicated function but it seems that the returned string is not always a valid JSON string. I had a parsing error on a SQL request due to indent. Here is our function :
function arrayToJSON ($array) {
$parts = array();
$is_list = false;
if ( is_array($array) && !$array ) return '[]' ;
//Find out if the given array is a numerical array
$keys = array_keys($array);
$max_length = count($array)-1;
if(($keys[0] === 0) and ($keys[$max_length] === $max_length)) {//See if the first key is 0 and last key is length - 1
$is_list = true;
for($i=0; $i<count($keys); $i++) { //See if each key correspondes to its position
if($i != $keys[$i]) { //A key fails at position check.
$is_list = false; //It is an associative array.
break;
}
}
}
foreach($array as $key=>$value) {
if(is_array($value)) { //Custom handling for arrays
if($is_list) $parts[] = arrayToJSON($value); /* :RECURSION: */
else $parts[] = '"' . $key . '":' . arrayToJSON($value); /* :RECURSION: */
} else {
$str = '';
if(!$is_list) $str = '"' . $key . '":';
//Custom handling for multiple data types
if(is_int($value) || is_float($value)){
$str .= $value; //Numbers
}elseif($value === false){
$str .= 'false'; //The booleans
}elseif($value === true){
$str .= 'true';
}elseif(is_object($value)){
$str .= '"' . '"';
}else{
$str .= '"' . str_replace(array('\\', '"',"\r\n","\n"),array('\\\\', '\\"',' ',' '),$value) . '"'; //All other things
}
$parts[] = $str;
}
}
$json = implode(',',$parts);
if($is_list) return '[' . $json . ']';//Return numerical JSON
return '{' . $json . '}';//Return associative JSON
}
And here is my JS quickfix to it :
version = JSON.parse(request.response.replace (/([\s]{4})|[\t]/g, `\\t`)).version;
The workaround I made is to replace multiple spaces with \t but I would like to make the function work properly. So my question is : was the parsing error due to this function or does it come from something else I may have missed ? And how could I make things go right ?