Convert object string to JSON

2019-01-02 17:17发布

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

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

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.

19条回答
后来的你喜欢了谁
2楼-- · 2019-01-02 17:53

You have to write round brackets, because without them eval will consider code inside curly brackets as block of commands.

var i = eval("({ hello: 'world', places: ['Africa', 'America', 'Asia', 'Australia'] })");
查看更多
登录 后发表回答