Saturday, June 1, 2024
 Popular · Latest · Hot · Upcoming
107
rated 0 times [  109] [ 2]  / answers: 1 / hits: 16743  / 11 Years ago, wed, july 17, 2013, 12:00:00

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


More From » json

 Answers
13

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


[#76939] Tuesday, July 16, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
brynnleslis

Total Points: 425
Total Questions: 100
Total Answers: 115

Location: Wallis and Futuna
Member since Tue, Mar 30, 2021
3 Years ago
;