With php I use json_encode to encode some values from a json array. These values are needed in a javascript file.
I noticed that php json_encode gives a string surrounded by square brackets "[ ]" and these brackets are not accepted by JSON.parse in javascript.
If I replace the square brackets by curly brackets "{ }" then JSON.parse is working fine.
json1 = '{"4":{"eng":"2","deu":"2"}}'; // json with curly brackets (works fine)
json2 = '["4":{"eng":"2","deu":"2"}]'; // json with square brackets (does not work)
test1 = validateJson( json1 ); // valid json
test2 = validateJson( json2 ); // invalid json
function validateJson( str ) {
let tmp;
try { tmp = JSON.parse( str ); } catch ( e ) {
console.error( 'INVALID JSON ' + str );
return false;
}
return tmp;
}
I don't know what the best solution is. Why are php json_encode and javascript JSON.parse not compatible? Is it json_encode who gives incorrect json? Or is it JSON.parse that can't read json properly?
In your opinion should I modify the json string server-side in php before sending it to javascript? Or should I rather find an alternative to JSON.parse? Do you have an idea what is the best thing to do? Any suggestion is welcome
Here is a complete example, if I visit this page there will be a javascript error in the console, which I don't understand why because this json seems valid:
<html>
<body>
<script>
json1 = '{"4":{"eng":"2","deu":"2"}}'; // json with curly brackets (works fine)
json2 = '["4":{"eng":"2","deu":"2"},"5":{"eng":"3","deu":"3"}]'; // json with square brackets (does not work)
test1 = validateJson( json1 ); // valid json
test2 = validateJson( json2 ); // invalid json
function validateJson( str ) {
let tmp;
try { tmp = JSON.parse( str ); } catch ( e ) {
console.error( 'INVALID JSON ' + str );
return false;
}
return tmp;
}
</script>
</body>
</html>```
Thank you very much :)