3

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.

4

1 回答 1

3

在 PHP 中的某个时刻,JSON 被编码了两次。为了使 JSON 有效,必须对引号进行转义。字符串是有效的 JSON:

"any string.  Quotes (\") can be included"

这可以重复编码,但它所做的只是在外部添加引号。

您的 PHP 代码似乎错误地调用json_encode了两次。您需要调用$.parseJSON多次json_encode

于 2013-06-05T02:30:50.650 回答