javascript JSON.stringify / 用引号解析奇怪
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18273687/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JSON.stringify / parse oddness with quote marks
提问by Gruffy
I am running into an odd little problem with parsing some JSON which has quotes in it. I am using the native JSON.stringify and JSON.parse functions to do this. If I stringify an object which an object which has quote marks in it, they are escaped as one would expect. If I then parse this back into an object, it again works fine.
我在解析一些带有引号的 JSON 时遇到了一个奇怪的小问题。我正在使用本机 JSON.stringify 和 JSON.parse 函数来执行此操作。如果我对一个对象进行字符串化,该对象中包含引号的对象,它们会按预期进行转义。如果我然后将其解析回一个对象,它又可以正常工作了。
The problem is occurring where I stringify, then print the object to a page, then parse the resulting string. If I try to do this, the parse function fails as stringify has only put single slashes before each of the offending quote marks.
问题发生在我字符串化,然后将对象打印到页面,然后解析生成的字符串的地方。如果我尝试这样做,解析函数将失败,因为 stringify 仅在每个有问题的引号之前放置了单斜杠。
The reason I need to achieve this is I am working on an application that dynamically loads content stored in a database as JSON strings. The strings at some point need to be printed onto the page somewhere so that the javascript can find them and build the page based on their contents. I need some way of robustly passing the object into and out of strings which will not fail if a user inputs the wrong characters!
我需要实现这一点的原因是我正在开发一个应用程序,该应用程序将存储在数据库中的内容作为 JSON 字符串动态加载。某些时候的字符串需要打印到页面的某个位置,以便 javascript 可以找到它们并根据它们的内容构建页面。我需要某种方法来稳健地将对象传入和传出字符串,如果用户输入错误的字符,它不会失败!
I can solve this for the moment by inserting extra slashes into the code with a replace call, but I was wondering if there is a better way to handle this?
我暂时可以通过使用替换调用在代码中插入额外的斜杠来解决这个问题,但我想知道是否有更好的方法来处理这个问题?
I have put together a couple of jsfiddles to illustrate what I am trying to describe:
我已经整理了几个 jsfiddles 来说明我想要描述的内容:
http://jsfiddle.net/qwUAJ/(Stringify then parse back)
http://jsfiddle.net/qwUAJ/(字符串化然后解析回来)
var ob = {};
ob["number1"] = 'Number "1"';
ob["number2"] = 'Number 2';
ob["number3"] = 'Number 3';
var string = JSON.stringify(ob);
var reOb = JSON.parse('{"number1":"Number \"1\"","number2":"Number 2","number3":"Number 3"}');
$('div').html(string);
http://jsfiddle.net/a3gBf/4/(Stringify, then print, then parse back)
http://jsfiddle.net/a3gBf/4/(字符串化,然后打印,然后解析回来)
// Make an object
var ob = {};
ob["number1"] = 'Number "1"';
ob["number2"] = 'Number 2';
ob["number3"] = 'Number 3';
// Turn the object into a JSON string
var string = JSON.stringify(ob);
// Printing the string outputs
// {"number1":"Number \"1\"","number2":"Number 2","number3":"Number 3"}
$('.stringified').html(string);
// Attempt to turn the printed string back into an object
var reOb = JSON.parse('{"number1":"Number \"1\"","number2":"Number 2","number3":"Number 3"}');
// This fails due to the single escaped quote marks.
Thank you for any help in advance!
提前感谢您的任何帮助!
回答by Paul S.
This is a problem which arises from re-evaluating a Stringwithout first converting it back into a string literal, so the meaning changes if it is even still valid.
You need to consider what does '\"'
as a literal actually mean? The answer is "
, without the \
. Why?
这是由于重新评估String而没有先将其转换回字符串文字而产生的问题,因此即使它仍然有效,其含义也会发生变化。
您需要考虑'\"'
作为字面的实际含义是什么?答案是"
,没有\
. 为什么?
\"
resolves to"
\"
决心"
If you want to have \"
as the result of the literal, you need to write '\\\"'
如果你想得到\"
文字的结果,你需要写'\\\"'
\\
resolves to\
\"
resolves to"
\\
决心\
\"
决心"
So basically, the extra slashes are required to escape any characters with special meaning in string literals.
所以基本上,需要额外的斜杠来转义字符串文字中具有特殊含义的任何字符。
If you did var reOb = JSON.parse($('.stringified').html());
it would work fine as is.
如果你这样做了,var reOb = JSON.parse($('.stringified').html());
它会正常工作。
Consider further
进一步考虑
str = '\\"\\''; // \"\'
str = '\"\''; // "'
str = '"''; // SyntaxError: Unexpected token ILLEGAL
As far as I'm aware, JavaScriptoffers no native implementation to convert strings as desired, so the easiest method I know of is using a replace
据我所知,JavaScript没有提供根据需要转换字符串的本机实现,所以我知道的最简单的方法是使用replace
function toLiteral(str) {
var dict = {'\b': 'b', '\t': 't', '\n': 'n', '\v': 'v', '\f': 'f', '\r': 'r'};
return str.replace(/([\'"\b\t\n\v\f\r])/g, function (//PHP code generating js code
echo "var myJSONString = \"". str_replace("\"","\\"",$mySqlJSON)."\";";
, ) {
return '\' + (dict[] || );
});
}
toLiteral('foo\bar'); // "foo\bar"
回答by HMR
If you generate JS with PHP code you should escape the quotes in your JSON string:
如果您使用 PHP 代码生成 JS,您应该转义 JSON 字符串中的引号:
##代码##