简体   繁体   English

JSON JavaScript:转义双引号? concat json与其他字符串

[英]json javascript: escape double quotes? concat json with other string

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. 问题是双引号搞砸了-my_dict中有引号,而my_form中有引号。 But isn't json supposed to be escaping the double qoutes? 但是json是否不应该逃脱双重qoutes? Is that not part of what it does? 那不是它的一部分吗? Or do I need to do this? 还是我需要这样做? Or is there some other way?? 还是有其他方法?

You need to encode the string for HTML, f.ex using RegExp: 您需要使用RegExp编码HTML,f.ex的字符串:

as_string = JSON.stringify(my_dict).replace(/\"/g,'&quot;');

Or use DOM Manipulation if possible. 或尽可能使用DOM操作。

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. 使用标准DOM,而不是innerHTML。 That will take care of escaping for you. 那会照顾您的逃生。

 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. 编码为JSON将转义JSON格式的引号。 You are then embedding the JSON in HTML, so you need to escape it for HTML too. 然后,您将JSON嵌入HTML中,因此也需要对HTML进行转义。 (Or, as I recommend above, bypass HTML and go direct to DOM manipulation). (或者,按照我上面的建议,绕过HTML并直接进行DOM操作)。

You could also use escape if 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

& unescape when you get the value back, UNESCAPE当你值回,

as_string = unescape(as_string)

// as_string : {"1":"hi you'll","2":"hello"}

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

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