简体   繁体   English

带有Ajax请求和“ \\\\ n”换行符的Javascript JSON.parse函数

[英]Javascript JSON.parse function with Ajax request and “\\n” new line escaped char

https://jsbin.com/zuhatujoqo/1/edit?js,console https://jsbin.com/zuhatujoqo/1/edit?js,console

Edit: json file has this line: 编辑:json文件具有以下行:

{"pd":"ciao \\n ste"}

I'm requesting a valid json file with an ajax call. 我正在使用ajax调用请求有效的json文件。
Then JSON.parse the result. 然后JSON.parse结果。

I don't understand what is happening with the "\\\\n" escaped new line char coming from my json file. 我不明白来自json文件的“ \\\\ n”转义换行符是怎么回事。

JSON.parse is giving me different result if i feed it with the same values. 如果我使用相同的值来输入JSON.parse,则会给我不同的结果。

var result = JSON.parse(data);
console.log(result);
var result2 = JSON.parse('{"pd":"ciao \\n ste"}');
console.log(result2);

As i understand it may be related to the fact that javascript before and then parse are escaping ( or unescaping ?? ) the string. 据我了解,这可能与以下事实有关:javascript之前和之后的解析都在转义(或转义??)字符串。

The problem is that i also don't understand this: 问题是我也不明白这一点:

result = result.replace(/\\n/g, "<br />");

do i also have to escape the regex itself? 我还必须逃避正则表达式本身吗?

Sum: I want to use the .json file loaded via Ajax. 总结:我想使用通过Ajax加载的.json文件。 I want the JSON.parse to do his job and unescape the "\\\\n" returning the NewLine char. 我希望JSON.parse做好他的工作,并取消转义“ \\\\ n”返回NewLine字符。

Thanks to the answers Bergi gave me, i now understand that the JSON.parse was already doing his job. 多亏了Bergi给我的答案,我现在知道JSON.parse已经在做他的工作了。 It was my fault, i was providing a json file with "\\\\n" inside instead of just "\\n". 这是我的错,我提供的是一个内含“ \\\\ n”的json文件,而不仅仅是“ \\ n”。

Here an updated jsbin where you can see that now JSON.parse acts the same in different scenario. 在这里更新了jsbin,您可以在其中看到JSON.parse在不同情况下的行为相同。 https://jsbin.com/xezipucili/1/edit?js,console https://jsbin.com/xezipucili/1/edit?js,console

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM