json javascript:转义双引号?将concat json与其他字符串 [英] json javascript: escape double quotes? concat json with other string

查看:371
本文介绍了json javascript:转义双引号?将concat json与其他字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JS中,我有一个字典,使用json(json2)进行字符串化:

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是一个字符串,因为它以DOM形式添加到文档中(创建节点,添加innerHTML,在文档中插入)

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

问题是双引号搞砸了-my_dict中有引号,而my_form中有引号.但是json是否不应该逃脱双重qoutes?那不是它的一部分吗?还是我需要这样做?还是有其他方法?

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_form是一个字符串,因为它以DOM形式添加到文档中(创建节点,添加innerHTML,在文档中插入)

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

通过将字符串粉碎在一起来生成代码比这更值得.不要这样使用标准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.

 var frm = document.createElement('form');
 var ipt = document.createElement('input');
 ipt.value = as_string;
 frm.appendChild(ipt);

但是json是否不应该转义双qoutes?

But isn't json supposed to be escaping the double qoutes?

编码为JSON将转义JSON格式的引号.然后,您将JSON嵌入HTML中,因此也需要对HTML进行转义. (或者,按照我上面的建议,绕过HTML并直接进行DOM操作).

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 javascript:转义双引号?将concat json与其他字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆