将对象字符串转换为JSON

将对象字符串转换为JSON

问题描述:

如何使用JavaScript(或jQuery)将描述对象的字符串转换为JSON字符串?

How can I convert a string that describes an object into a JSON string using JavaScript (or jQuery)?

例如:转换它( NOT 一个有效的JSON字符串):

e.g: Convert this (NOT a valid JSON string):

var str = "{ hello: 'world', places: ['Africa', 'America', 'Asia', 'Australia'] }"

进入:

str = '{ "hello": "world", "places": ["Africa", "America", "Asia", "Australia"] }'

我很想避免如果可能,使用 eval()

I would love to avoid using eval() if possible.

如果字符串来自可靠来源,您可以使用 eval 然后 JSON.stringify 结果。像这样:

If the string is from a trusted source, you could use eval then JSON.stringify the result. Like this:

var str = "{ hello: 'world', places: ['Africa', 'America', 'Asia', 'Australia'] }";
var json = JSON.stringify(eval("(" + str + ")"));

注意当你 eval 一个对象文字,它必须用括号括起来,否则大括号被解析为一个块而不是一个对象。

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.

我也同意这个问题下的评论。最好只在有效的JSON中编码对象开始,并避免必须解析,编码,然后可能再次解析 。 HTML支持单引号属性(只需确保对字符串中的任何单引号进行HTML编码)。

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