json javascript:转义双引号?将 json 与其他字符串连接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17696579/
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 javascript: escape double quotes? concat json with other string
提问by user984003
In JS, I have a dictionary that I stringify with json (json2):
在 JS 中,我有一个用 json (json2) 字符串化的字典:
my_dict = {"1":"hi you'll", "2":"hello"};
as_string = JSON.stringify(my_dict);
I need to add this as a value to a form, but the form itself starts out as a string:
我需要将此作为值添加到表单中,但表单本身以字符串开头:
var my_form = '<form><input value = "'+as_string+'"></form>'
my_form is a string because it gets added to the document as DOM (create node, add innerHTML, insert in document)
my_form 是一个字符串,因为它作为 DOM 添加到文档中(创建节点,添加 innerHTML,插入文档)
The issue is that the double quotes get screwed up - there are quotes in my_dict and quotes in my_form. But isn't json supposed to be escaping the double qoutes? Is that not part of what it does? Or do I need to do this? Or is there some other way??
问题是双引号搞砸了——my_dict 中有引号,my_form 中有引号。但是 json 不是应该逃避双重 qoutes 吗?这不是它所做的一部分吗?或者我需要这样做吗?还是有其他方法??
回答by David Hellsing
You need to encode the string for HTML, f.ex using RegExp:
您需要使用 RegExp 为 HTML、f.ex 编码字符串:
as_string = JSON.stringify(my_dict).replace(/\"/g,'"');
Or use DOM Manipulation if possible.
或者尽可能使用 DOM 操作。
回答by Quentin
my_form is a string because it gets added to the document as DOM (create node, add innerHTML, insert in document)
my_form 是一个字符串,因为它作为 DOM 添加到文档中(创建节点,添加 innerHTML,插入文档)
Generating code by smashing together strings is more pain then it is worth. Don't do it. Use standard DOM, not innerHTML. That will take care of escaping for you.
通过将字符串粉碎在一起来生成代码是更痛苦的,而不是值得的。不要这样做。使用标准 DOM,而不是 innerHTML。这将照顾你逃脱。
var frm = document.createElement('form');
var ipt = document.createElement('input');
ipt.value = as_string;
frm.appendChild(ipt);
But isn't json supposed to be escaping the double qoutes?
但是 json 不是应该逃避双重 qoutes 吗?
Encoding as JSON will escape the quotes for the JSON format. You are then embedding the JSON in HTML, so you need to escape it for HTML too. (Or, as I recommend above, bypass HTML and go direct to DOM manipulation).
编码为 JSON 将转义 JSON 格式的引号。然后您将 JSON 嵌入到 HTML 中,因此您也需要为 HTML 转义它。(或者,正如我上面建议的,绕过 HTML 并直接进行 DOM 操作)。
回答by loxxy
You could also use escapeif you just want to keep it in the DOM:
如果您只想将其保留在 DOM 中,也可以使用转义:
my_dict = {"1":"hi you'll", "2":"hello"};
as_string = escape(JSON.stringify(my_dict));
// as_string : %7B%221%22%3A%22hi%20you%27ll%22%2C%222%22%3A%22hello%22%7D
& unescapewhen you get the value back,
&当你得到价值时unescape,
as_string = unescape(as_string)
// as_string : {"1":"hi you'll","2":"hello"}