Javascript 将对象字符串转换为 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9036429/
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
Convert object string to JSON
提问by snorpey
How can I convert a string that describes an object into a JSON string using JavaScript (or jQuery)?
如何使用 JavaScript(或 jQuery)将描述对象的字符串转换为 JSON 字符串?
e.g: Convert this (NOTa valid JSON string):
例如:转换这个(不是有效的 JSON 字符串):
var str = "{ hello: 'world', places: ['Africa', 'America', 'Asia', 'Australia'] }"
into this:
进入这个:
str = '{ "hello": "world", "places": ["Africa", "America", "Asia", "Australia"] }'
I would love to avoid using eval()
if possible.
eval()
如果可能的话,我很想避免使用。
回答by Matthew Crumley
If the string is from a trusted source, you could use eval
then JSON.stringify
the result. Like this:
如果字符串是来自可靠来源,你可以使用eval
然后JSON.stringify
的结果。像这样:
var str = "{ hello: 'world', places: ['Africa', 'America', 'Asia', 'Australia'] }";
var json = JSON.stringify(eval("(" + str + ")"));
Note that when you eval
an object literal, it has to be wrapped in parentheses, otherwise the braces are parsed as a block instead of an object.
请注意,当您eval
使用对象字面量时,它必须包含在括号中,否则大括号将被解析为块而不是对象。
I also agree with the comments under the question that it would be much better to just encode the object in valid JSON to begin with and avoid having to parse, encode, then presumably parse it again. HTML supports single-quoted attributes (just be sure to HTML-encode any single quotes inside strings).
我也同意问题下的评论,即开始时只用有效的 JSON 对对象进行编码并避免解析、编码,然后大概再次解析它会更好。HTML 支持单引号属性(只需确保对字符串内的任何单引号进行 HTML 编码)。
回答by Rocket Hazmat
Your string is not valid JSON, so JSON.parse
(or jQuery's $.parseJSON
) won't work.
您的字符串不是有效的 JSON,因此JSON.parse
(或 jQuery 的$.parseJSON
)将不起作用。
One way would be to use eval
to "parse" the "invalid" JSON, and then stringify
it to "convert" it to valid JSON.
一种方法是使用eval
“解析”“无效”JSON,然后stringify
将其“转换”为有效的 JSON。
var str = "{ hello: 'world', places: ['Africa', 'America', 'Asia', 'Australia'] }"
str = JSON.stringify(eval('('+str+')'));
I suggest instead of trying to "fix" your invalid JSON, you start with valid JSON in the first place. How is str
being generated, it should be fixed there, before it's generated, not after.
我建议不要尝试“修复”无效的 JSON,而是首先从有效的 JSON 开始。str
它是如何生成的,应该在它生成之前而不是之后固定在那里。
EDIT: You said (in the comments) this string is stored in a data attribute:
编辑:您说(在评论中)此字符串存储在数据属性中:
<div data-object="{hello:'world'}"></div>
I suggest you fix it here, so it can just be JSON.parse
d. First, both they keys and values need to be quoted in double quotes. It should look like (single quoted attributes in HTML are valid):
我建议你在这里修复它,所以它可以只是JSON.parse
d。首先,它们的键和值都需要用双引号引起来。它应该看起来像(HTML 中的单引号属性是有效的):
<div data-object='{"hello":"world"}'></div>
Now, you can just use JSON.parse
(or jQuery's $.parseJSON
).
现在,您可以使用JSON.parse
(或 jQuery 的$.parseJSON
)。
var str = '{"hello":"world"}';
var obj = JSON.parse(str);
回答by Farmor
str = jQuery.parseJSON(str)
Edit. This is provided you have a valid JSON string
编辑。前提是您有一个有效的 JSON 字符串
回答by Ronald
Use simple code in the link below :
在下面的链接中使用简单的代码:
http://msdn.microsoft.com/es-es/library/ie/cc836466%28v=vs.94%29.aspx
http://msdn.microsoft.com/es-es/library/ie/cc836466%28v=vs.94%29.aspx
var jsontext = '{"firstname":"Jesper","surname":"Aaberg","phone":["555-0100","555-0120"]}';
var contact = JSON.parse(jsontext);
and reverse
并反转
var str = JSON.stringify(arr);
回答by allenhwkim
I hope this little function converts invalid JSON string to valid one.
我希望这个小函数将无效的 JSON 字符串转换为有效的字符串。
function JSONize(str) {
return str
// wrap keys without quote with valid double quote
.replace(/([$\w]+)\s*:/g, function(_, ){return '"'++'":'})
// replacing single quote wrapped ones to double quote
.replace(/'([^']+)'/g, function(_, ){return '"'++'"'})
}
Result
结果
var invalidJSON = "{ hello: 'world',foo:1, bar : '2', foo1: 1, _bar : 2, : 3, 'xxx': 5, \"fuz\": 4, places: ['Africa', 'America', 'Asia', 'Australia'] }"
JSON.parse(invalidJSON)
//Result: Uncaught SyntaxError: Unexpected token h VM1058:2
JSON.parse(JSONize(invalidJSON))
//Result: Object {hello: "world", foo: 1, bar: "2", foo1: 1, _bar: 2…}
回答by Tomalak
Use with caution (because of eval()
):
谨慎使用(因为eval()
):
function strToJson(str) {
eval("var x = " + str + ";");
return JSON.stringify(x);
}
call as:
调用为:
var str = "{ hello: 'world', places: ['Africa', 'America', 'Asia', 'Australia'] }";
alert( strToJson(str) );
回答by gonchuki
Disclaimer: don't try this at home, or for anything that requires other devs taking you seriously:
免责声明:不要在家里尝试这个,或者任何需要其他开发人员认真对待你的东西:
JSON.stringify(eval('(' + str + ')'));
There, I did it.
Try not to do it tho, eval is BAD for you. As told above, use Crockford's JSON shim for older browsers (IE7 and under)
在那里,我做到了。
尽量不要这样做, eval 对你不利。如上所述,对旧浏览器(IE7 及以下)使用 Crockford 的 JSON shim
This method requires your string to be valid javascript, which will be converted to a javascript object that can then be serialized to JSON.
此方法要求您的字符串是有效的javascript,它将被转换为一个 javascript 对象,然后可以将其序列化为 JSON。
edit:fixed as Rocket suggested.
编辑:修复为火箭建议。
回答by tokkonopapa
I put my answer for someone who are interested in this old thread.
我为对这个旧线程感兴趣的人提供了答案。
I created the HTML5 data-* parserfor jQuery plugin and demowhich convert a malformed JSON string into a JavaScript object without using eval()
.
我为 jQuery 插件和演示创建了HTML5 data-* 解析器,它将格式错误的 JSON 字符串转换为 JavaScript 对象,而不使用.eval()
It can pass the HTML5 data-* attributes bellow:
它可以传递以下 HTML5 data-* 属性:
<div data-object='{"hello":"world"}'></div>
<div data-object="{hello:'world'}"></div>
<div data-object="hello:world"></div>
into the object:
进入对象:
{
hello: "world"
}
回答by csuwldcat
There's a much simpler way to accomplish this feat, just hiHyman the onclick attribute of a dummy element to force a return of your string as a JavaScript object:
有一个更简单的方法来完成这个壮举,只需劫持一个虚拟元素的 onclick 属性来强制你的字符串作为 JavaScript 对象返回:
var jsonify = (function(div){
return function(json){
div.setAttribute('onclick', 'this.__json__ = ' + json);
div.click();
return div.__json__;
}
})(document.createElement('div'));
// Let's say you had a string like '{ one: 1 }' (malformed, a key without quotes)
// jsonify('{ one: 1 }') will output a good ol' JS object ;)
Here's a demo:http://codepen.io/csuwldcat/pen/dfzsu(open your console)
这是一个演示:http : //codepen.io/csuwldcat/pen/dfzsu(打开你的控制台)
回答by Seth
Douglas Crockford has a converter, but I'm not sure it will help with bad JSON to good JSON.
Douglas Crockford 有一个转换器,但我不确定它是否有助于将坏的 JSON 转换为好的 JSON。