带双引号的json解析错误 [英] json parse error with double quotes

查看:346
本文介绍了带双引号的json解析错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

双重引用即使转义也会抛出解析错误。

查看下面的代码

A double quote even if escaped is throwing parse error.
look at the code below

//parse the json in javascript  
var testJson = '{"result": ["lunch", "\"Show\""] }';  
var tags = JSON.parse(testJson);  
alert (tags.result[1]);

由于双引号(已经转义),这是抛出解析错误。

即使 eval()也不会在这里工作。

但如果我用这样的双斜杠转义它:

This is throwing parse error because of the double quotes (which are already escaped).
Even eval() won't work here.
But if i escape it with double slashes like this:

var result = '{"result": ["lunch", "\\"Show\\""] }';  
var tags = JSON.parse(result);  
alert (tags.result[1]);

然后它工作正常。

为什么我们需要在这里使用双斜杠在JavaScript中?
问题是PHP json_encode()函数使用单斜杠转义双引号(如下所示: \show\ JSON.parse 将无法解析。我如何处理这种情况?

then it works fine.
Why do we need to use double slash here in javascript? The problem is that PHP json_encode() function escapes a double quote with a single slash (like this: \"show\") which JSON.parse won't be able to parse. How do i handle this situation?

推荐答案

好吧,最后,JSON的解析使用相同的eval,所以当你给出时没有区别他们笑了。语法不正确。在这种情况下,你必须在php中正确地转义你的引号,然后用json_encode转义它们和它们的转义斜杠

Well, finally, JSON's parse uses the same eval, so there's no difference when you give them smth. with incorrect syntax. In this case you have to escape correctly your quotes in php, and then escape them and their escaping slashes with json_encode

<?php
    $json = '{"result": ["lunch", "\"Show\""] }';
    echo json_encode($json);
?>

OUTPUT: "{\"result\": [\"lunch\", \"\\\"Show\\\"\"] }"

这应该适用于客户端JS(如果我没有输入拼写错误)。

This should work on client-side JS (if I've made no typos).

这篇关于带双引号的json解析错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆