json解析错误,带双引号

发布于 2024-07-22 18:02:49 字数 634 浏览 9 评论 0原文

即使转义双引号也会引发解析错误。
看下面的代码,

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

由于双引号(已经转义),这会引发解析错误。
即使 eval() 在这里也不起作用。
但如果我像这样用双斜杠转义它:

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

那么它就可以正常工作。
为什么我们需要在 JavaScript 中使用双斜杠? 问题是 PHP json_encode() 函数用单斜杠转义双引号(如下所示:\"show\"),而 JSON.parse 将无法解析。 我该如何处理这种情况?

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]);

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]);

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

不知所踪 2024-07-29 18:02:49

Javascript 对其字符串进行转义,json 也对它们进行转义。
第一个字符串 ( '{"result": ["lunch", "\"Show\""] }' ) 被 json 解析器视为
{"result": ["lunch", ""Show""] },因为 javascript 中的 \" 表示 ",但事实并非如此t 退出双引号字符串。

第二个字符串 '{"result": ["lunch", "\\\"Show\\\""] }' 首先未转义为 {"result": ["lunch ", "\"Show\""] } (并且 json 正确地未转义)。

我认为, '{"result": ["lunch", "\\"Show\\""] }' 也应该有效。

Javascript unescapes its strings and json unescapes them as well.
the first string ( '{"result": ["lunch", "\"Show\""] }' ) is seen by the json parser as
{"result": ["lunch", ""Show""] }, because \" in javascript means ", but doesn't exit the double quoted string.

The second string '{"result": ["lunch", "\\\"Show\\\""] }' gets first unescaped to {"result": ["lunch", "\"Show\""] } (and that is correctly unescaped by json).

I think, that '{"result": ["lunch", "\\"Show\\""] }' should work too.

何以心动 2024-07-29 18:02:49

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

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

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

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

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\\\"\"] }"

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

绾颜 2024-07-29 18:02:49

这个问题是由两重字符串转义机制造成的:一是来自JS,一是来自JSON。

反斜杠字符与另一个后续字符的组合用于表示字符串中无法表示的一个字符
''\\'' 代表 '\' 等。

这种转义机制发生在 JSON.parse() 工作之前。

例如,

var parsedObj = JSON.parse('{"sentence": "It is one backslash(\\\\)"}');
console.log(parsedObj.sentence);
>>>"It is one backslash(\)"

从字符串生成器的角度来看,它将四个反斜杠“\”传递到 JavaScript 解释器中。

从 JavaScript 解释器的角度来看,它解释有两个反斜杠(\),因为每个“\\”序列将被解释为一个“\”。

从 JSON 解析器的角度来看,它接收到两个反斜杠(\\),并且 JSON 字符串转义规则会将其解析为单个“\”,即输出结果。

先解释一下代码:

var testJson = '{"result": ["lunch", "\"Show\""] }';
//The real string after sequence escaping in to JS is
//'{"result": ["lunch", ""Show""] }' 
//which is passed into the JSON.parse.
//Thus, it breaks the JSON grammar and generates an error
var tags = JSON.parse(testJson);  
alert (tags.result[1]);

This problem is caused by the two-folded string escaping mechanism: one comes from JS and one comes from JSON.

A combination of the backslash character combined with another following character is used to represent one character that is not otherwise representable within the string.
''\\'' stands for '\' etc.

This escaping mechanism takes place before JSON.parse() works.

For Example,

var parsedObj = JSON.parse('{"sentence": "It is one backslash(\\\\)"}');
console.log(parsedObj.sentence);
>>>"It is one backslash(\)"

From the string generator's perspective, it passes four backlashes '\' into the JavaScript interpretor.

From the JavaScript interpretor's perspective, it inteprets there are two backlashes(\) as each '\\' sequence will be interpreted as one '\'.

From the JSON parser's perspective, it receives two backlashes(\\) and the JSON string escape rules will parses it as one single '\' which is the output result.

Explain you first code:

var testJson = '{"result": ["lunch", "\"Show\""] }';
//The real string after sequence escaping in to JS is
//'{"result": ["lunch", ""Show""] }' 
//which is passed into the JSON.parse.
//Thus, it breaks the JSON grammar and generates an error
var tags = JSON.parse(testJson);  
alert (tags.result[1]);
怪异←思 2024-07-29 18:02:49

来自 文档

JSON_HEX_APOS(整数)所有 ' 均转换为 \u0027
JSON_HEX_QUOT(整数)所有“都转换为\u0022

json_encode() 需要两个参数,即值和选项。所以尝试一下,

json_encode($result, JSON_HEX_QUOT); // or
json_encode($result, JSON_HEX_QUOT | JSON_HEX_APOS);

但我还没有尝试过。

From the docs

JSON_HEX_APOS (integer) All ' are converted to \u0027
JSON_HEX_QUOT (integer) All " are converted to \u0022

json_encode() takes two args, the value and options. So try

json_encode($result, JSON_HEX_QUOT); // or
json_encode($result, JSON_HEX_QUOT | JSON_HEX_APOS);

I haven't tried this though.

树深时见影 2024-07-29 18:02:49

php 到 javascript 对象 (php >= 5.3.0)

var storesLocations = JSON.parse('<?php echo addslashes(json_encode($storesLocations,JSON_HEX_APOS | JSON_HEX_QUOT)) ?>');

php to javascript Object (php >= 5.3.0)

var storesLocations = JSON.parse('<?php echo addslashes(json_encode($storesLocations,JSON_HEX_APOS | JSON_HEX_QUOT)) ?>');
凉城已无爱 2024-07-29 18:02:49

关闭 php.ini 中的 magic_quotes_gpc

Turn off magic_quotes_gpc in php.ini.

ペ泪落弦音 2024-07-29 18:02:49

如果添加了标准 C 转义符,则 JSON.parse 会将 \" 等序列转换为 "\\ 转换为 \\n 转换为换行符,等等。

'foo\\bar\nbaz"' === JSON.parse('"foo\\\\bar\\nbaz\\""')

在我们的项目中:

原始字符串 ""{\"lat\":28.4594965,\ "lng\":77.0266383}""

传递到 JSON.parse() 后,

"{"lat":28.4594965,"lng":77.0266383}"

第 2nd 传递到 JSON.parse()

{lat: 28.4594965, lng: 77.0266383}

请注意,JSON.parse() 删除了转义字符,而不是将 string 转换为 object

删除转义字符后,字符串到对象的转换就开始工作了。

这是演示:

while (typeof p1 != 'object') {
  p1 = JSON.parse(p1);
  pass++;
  console.log('On pass ', pass, p1);
}

If the standard C escapes are added, then JSON.parse will convert sequences like \" into ", \\ into \, \n into a line-feed, etc.

'foo\\bar\nbaz"' === JSON.parse('"foo\\\\bar\\nbaz\\""')

In our project's case:

original string ""{\"lat\":28.4594965,\"lng\":77.0266383}""

After passing to JSON.parse()

"{"lat":28.4594965,"lng":77.0266383}"

On 2nd pass to JSON.parse()

{lat: 28.4594965, lng: 77.0266383}

Notice that JSON.parse() removed escaping characters instead of converting string to object.

After the escaping characters were removed, the string to object conversion worked.

Here is the demo:

while (typeof p1 != 'object') {
  p1 = JSON.parse(p1);
  pass++;
  console.log('On pass ', pass, p1);
}
白云悠悠 2024-07-29 18:02:49

这可能有帮助:

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

This might help:

<?php
$json = '{"result": ["lunch", "\"Show\""] }';
echo addslashes(json_encode($json));
烟雨凡馨 2024-07-29 18:02:49

尝试这个。 然后尝试评论

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<pre><?php ($_POST)?print_r($_POST):'' ?></pre>

<form method="POST">
    <input type="text" name="name"><br>
    <input type="email" name="email"><br>
    <input type="time" name="time"><br>
    <input type="date" name="date"><br>
    <input type="hidden" name="id"><br>
    <textarea name="detail"></textarea>
    <input type="submit" value="Submit"><br>
</form>
<?php 
/* data */
$data = [
            'name'=>'vinay"'."'\\\\",
            'email'=>'[email protected]',
            'time'=>date('H:i:00'),
            'date'=>date('Y-m-d'),
            'detail'=>'Try this var_dump(0=="ZERO") \\ \\"'." ' \\\\    ",
            'id'=>123,
        ];
?>
<span style="display: none;" class="ajax-data"><?=json_encode($data)?></span>
<script type="text/javascript">
    /* Error */
    // var json = JSON.parse('<?=json_encode($data)?>');
    /* Error solved */
    var json = JSON.parse($('.ajax-data').html());
    console.log(json)
    /* automatically assigned value by name attr */
    for(x in json){
        $('[name="'+x+'"]').val(json[x]);
    }
</script>

Try This. and then try commented

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<pre><?php ($_POST)?print_r($_POST):'' ?></pre>

<form method="POST">
    <input type="text" name="name"><br>
    <input type="email" name="email"><br>
    <input type="time" name="time"><br>
    <input type="date" name="date"><br>
    <input type="hidden" name="id"><br>
    <textarea name="detail"></textarea>
    <input type="submit" value="Submit"><br>
</form>
<?php 
/* data */
$data = [
            'name'=>'vinay"'."'\\\\",
            'email'=>'[email protected]',
            'time'=>date('H:i:00'),
            'date'=>date('Y-m-d'),
            'detail'=>'Try this var_dump(0=="ZERO") \\ \\"'." ' \\\\    ",
            'id'=>123,
        ];
?>
<span style="display: none;" class="ajax-data"><?=json_encode($data)?></span>
<script type="text/javascript">
    /* Error */
    // var json = JSON.parse('<?=json_encode($data)?>');
    /* Error solved */
    var json = JSON.parse($('.ajax-data').html());
    console.log(json)
    /* automatically assigned value by name attr */
    for(x in json){
        $('[name="'+x+'"]').val(json[x]);
    }
</script>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文