简体   繁体   中英

json javascript: escape double quotes? concat json with other string

In JS, I have a dictionary that I stringify with 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)

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??

You need to encode the string for HTML, f.ex using RegExp:

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

Or use DOM Manipulation if possible.

my_form is a string because it gets added to the document as DOM (create node, add innerHTML, insert in document)

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.

 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?

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).

You could also use escape if you just want to keep it in the 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,

as_string = unescape(as_string)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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