今天晚上挖掘了一些项目代码,我遇到了类似于此的一行jQuery:
jQuery.parseJSON(jQuery.parseJSON(json_string)));
我很好奇为什么这些电话是嵌套的。仔细看看JSON字符串,我发现它包含斜杠(显然是转义引号 - 这是一个PHP项目)。 JSON字符串与此类似:
"[{\"input_index\": 0, \"secondary_index\": 0, \"street_address\": \"14106 Transportation Ave\", \"last_line\": \"Kennedy Building\"}]"
我把呼叫分开了:
var res1 = jQuery.parseJSON(json_string);
var res2 = jQuery.parseJSON(res1);
我发现第一次调用产生了另一个JSON字符串,删除了斜杠,类似于:
[{"input_index": 0, "secondary_index": 0, "street_address": "14106 Transportation Ave", "last_line": "Kennedy Building"}]
第二次调用jQuery.parseJSON实际上产生了一个javascript对象。
为什么会这样?我希望第一次调用失败。
jQuery documentation here没有提到这样的行为。当然,我仍然是jQuery的新手,所以我可能会错过这个显而易见的事情。
答案 0 :(得分:3)
在PHP的某些时候,JSON被编码两次。必须转义引号才能使JSON有效。字符串是有效的JSON:
"any string. Quotes (\") can be included"
这可以重复编码,但它所做的就是在外面添加引号。
好像你的PHP代码错误地调用了json_encode
两次。您需要多次调用$.parseJSON
json_encode
。