今晚在研究一些项目代码时,我遇到了类似于这样的 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 还很陌生,所以我可能错过了显而易见的事情。
最佳答案
在 PHP 中的某个时刻,JSON 被编码两次。必须对引号进行转义才能使 JSON 有效。字符串是有效的 JSON:
"any string. Quotes (\") can be included"
这可以重复编码,但它所做的只是在外部添加引号。
您的 PHP 代码似乎错误地调用了 json_encode
两次。您需要调用 $.parseJSON
的次数与调用 json_encode
的次数一样多。
关于jquery - 为什么 jQuery.parseJSON 从 JSON 字符串中删除斜杠?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16930364/