Digging through some project code this evening, I ran across a line of jQuery similar to this:
jQuery.parseJSON(jQuery.parseJSON(json_string)));
I was curious as to why the calls were nested. Taking a closer look at the JSON string, I found that it contained slashes (apparently escaping the quotes - this is a PHP project). The JSON string is similar to this:
"[{\"input_index\": 0, \"secondary_index\": 0, \"street_address\": \"14106 Transportation Ave\", \"last_line\": \"Kennedy Building\"}]"
I separated the calls like so:
var res1 = jQuery.parseJSON(json_string);
var res2 = jQuery.parseJSON(res1);
I found that the first call produced another JSON string, with the slashes removed, similar to this:
[{"input_index": 0, "secondary_index": 0, "street_address": "14106 Transportation Ave", "last_line": "Kennedy Building"}]
The second call to jQuery.parseJSON actually produced a javascript object.
Why does this occur? I would expect the first call to fail.
The jQuery documentation here doesn't mention behavior like this. Granted, I'm still fairly new to jQuery, so I may be missing the obvious.
At some point in PHP the JSON is being encoded twice. Quotes have to be escaped in order to make the JSON valid. Strings are valid JSON:
"any string. Quotes (\") can be included"
This can be encoded repeatedly, but all it would do is add quotes to the outside.
It seems like your PHP code is incorrectly calling json_encode twice. You need to call $.parseJSON as many times as json_encode is called.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With