如何将此 javascript 字符串转换为 javascript 数组/对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7744449/
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
How to convert this javascript string into javascript array/object
提问by user991987
Possible Duplicate:
How to parse JSON easily?
可能的重复:
如何轻松解析 JSON?
I have this string:
我有这个字符串:
[{text: 'First Option', value: 'first'},{text: 'Second Option', value: 'second'},{text: 'Third Option', value: 'third'}]
How do I convert it into an array/object in the same form in javascript?
如何在javascript中将其转换为相同形式的数组/对象?
回答by Ritesh Mengji
Could either use var data = JSON.parse(yourString);or var data = eval('(' + yourString+ ')');
可以使用var data = JSON.parse(yourString);或var data = eval('(' + yourString+ ')');
回答by James Allardice
This is one of the times that evalactually comes in useful:
这是eval真正有用的时间之一:
var x = eval(yourString);
But it's definitely safer to use JSON.parseas suggested by other answers.
但是JSON.parse按照其他答案的建议使用绝对更安全。
Here's a working exampleof the evalversion.
这是该版本的一个工作示例eval。
回答by Clive
Use JSON.parse
使用 JSON.parse
var obj = JSON.parse(str);
回答by Brian Hoover
Just set a variable to exactly that string.
只需将变量设置为该字符串即可。
var new_object = [{text: 'First Option', value: 'first'},{text: 'Second Option', value: 'second'},{text: 'Third Option', value: 'third'}]
回答by Brad Christie
If you jave jQuery, you can use jQuery.parseJSON. If you don't you can pull the function from the source codeand place it on your page and have the same advantages.
如果您使用 jQuery,则可以使用jQuery.parseJSON. 如果您不这样做,您可以从源代码中提取该功能并将其放置在您的页面上并具有相同的优势。

