Javascript 如何使用 JSON 文字字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3153723/
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
How to use a JSON literal string?
提问by SBUJOLD
Since the JSON format specifies that single quotes should not be escaped, most libraries (or even the native JSON parser) will fail if you have an escaped single quote in it. Now this usually is not a problem since most of the time you do an XHR that fetches some data formatted as JSON and you use the responseText which contains your JSON string that you can then parse, etc.
由于 JSON 格式指定不应转义单引号,因此如果其中包含转义的单引号,大多数库(甚至本地 JSON 解析器)都会失败。现在这通常不是问题,因为大多数时候您执行 XHR 来获取一些格式为 JSON 的数据,并且您使用包含您可以解析的 JSON 字符串的 responseText,等等。
In this particular situation, I have a JSON string stored in a database as text... so the database contains something like {"property":"value"}and I want to output this as part of an HTML page created by the server so that the JavaScript code in that page looks something like this:
在这种特殊情况下,我有一个 JSON 字符串作为文本存储在数据库中......所以数据库包含类似的内容{"property":"value"},我想将其作为服务器创建的 HTML 页面的一部分输出,以便该页面中的 JavaScript 代码看起来像这样:
var x = '{"property":"value"}';
Now if the JSON string in the database contains a single quote like this:
现在,如果数据库中的 JSON 字符串包含这样的单引号:
{"property":"val'ue"}
Then I need to escape it or else I will never be able to use it as a string:
然后我需要转义它,否则我将永远无法将它用作字符串:
console.clear();
var obj = {prop:"val'ue"};
var str = JSON.stringify(obj);
console.log("JSON string is %s",str);
console.dir(JSON.parse(str)); //No problem here
//This obviously can't work since the string is closed and it causes an invalid script
//console.dir(JSON.parse('{prop:"val'ue"}'));
//so I need to escape it to use a literal JSON string
console.dir(JSON.parse('{"prop":"val\'ue"}'));
The question then is why {"prop":"val\'ue"}not considered a valid JSON string ?
那么问题是为什么{"prop":"val\'ue"}不考虑有效的 JSON 字符串?
采纳答案by gnarf
In JavaScript - the string '{"prop":"val\'ue"}'is acorrect way to encode the JSON as a string literal.
在 JavaScript 中 - 字符串'{"prop":"val\'ue"}'是将 JSON 编码为字符串文字的正确方法。
As the JavaScript interpreter reads the single-quoted string, it will convert the \'to '. The valueof the string is {"prop":"val'ue"}which is valid JSON.
由于JavaScript解释器读取单引号的字符串,它会转换\'到'。字符串的值{"prop":"val'ue"}是有效的 JSON。
In order to create the invalidJSON string, you would have to write '{"prop":"val\\\'ue"}'
为了创建无效的JSON 字符串,您必须编写'{"prop":"val\\\'ue"}'
If I understand the question right, you are trying to generate JavaScript code that will set some variable to the decoded version of a JSON string you have stored in the database. So now you are encoding the string again, as the way to get this string into JavaScript is to use a string literal, passing it through JSON.parse(). You can probably rely on using the server side JSON encoder to encode the JSON string as a JavaScript string literal. For instance:
如果我理解正确,您正在尝试生成 JavaScript 代码,该代码将一些变量设置为您存储在数据库中的 JSON 字符串的解码版本。所以现在您再次对字符串进行编码,因为将这个字符串导入 JavaScript 的方法是使用字符串文字,通过JSON.parse(). 您可能可以依靠使用服务器端 JSON 编码器将 JSON 字符串编码为 JavaScript 字符串文字。例如:
<?php $jsonString = '{"prop":"val\'ue"}'; ?>
var myJson = JSON.parse(<?php echo json_encode($jsonString) ?>);
// Prints out:
// var myJson = JSON.parse("{\"prop\":\"val'ue\"}");
// And results: Object - { prop: "val'ue"}
However, If you are 100% sure the JSON is going to be valid, and don't need the weight of the extra parsing / error checking - you could skip all that extra encoding and just write:
但是,如果您 100% 确定 JSON 将是有效的,并且不需要额外解析/错误检查的权重 - 您可以跳过所有额外的编码,只需编写:
var myJson = <?php echo $jsonString; ?>
Remember, JSON is valid JavaScript syntax for defining objects after all!
请记住,JSON 毕竟是用于定义对象的有效 JavaScript 语法!
回答by amelvin
According to jsonlintit is valid without escaping the single quote, so this is fine:
根据jsonlint它在不转义单引号的情况下是有效的,所以这很好:
{"prop": "val'ue"}
But this is invalid:
但这是无效的:
{"prop":"val\'ue"}
According to json.orgjson:
根据json.orgjson:
is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others
完全独立于语言,但使用 C 系列语言程序员熟悉的约定,包括 C、C++、C#、Java、JavaScript、Perl、Python 和许多其他语言
So it is the language conventions in c-type languages regarding the reverse solidus (\) that means that your example is not valid.
因此,c 类型语言中关于反斜线 (\) 的语言约定意味着您的示例无效。
回答by Jesse Brown
You might try the following, however, it's ugly.
您可以尝试以下方法,但是,它很难看。
JSON.parse("{\"obj\":\"val'ue\"}");
JSON.parse("{\"obj\":\"val'ue\"}");
Or just store the string to a var first. This should not store the literal backslash value and therefore the JSON parser should work.
或者只是先将字符串存储到 var 中。这不应该存储文字反斜杠值,因此 JSON 解析器应该可以工作。
var str = '{"obj" : "val\'ue"}';
JSON.parse(str);

