将 JSON 字符串转换为 Javascript 中的 JSON 对象数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4375537/
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 JSON string to array of JSON objects in Javascript
提问by Sobis
I would like to convert this string
我想转换这个字符串
{"id":1,"name":"Test1"},{"id":2,"name":"Test2"}
to array of 2 JSON objects. How should I do it?
到 2 个 JSON 对象的数组。我该怎么做?
best
最好的事物
回答by darioo
Using jQuery:
使用jQuery:
var str = '{"id":1,"name":"Test1"},{"id":2,"name":"Test2"}';
var jsonObj = $.parseJSON('[' + str + ']');
jsonObj
is your JSON object.
jsonObj
是您的 JSON 对象。
回答by AnarchistGeek
As Luca indicated, add extra []
to your string and use the code below:
正如 Luca 所指出的,[]
在您的字符串中添加额外内容并使用以下代码:
var myObject = eval('(' + myJSONtext + ')');
to test it you can use the snippet below.
要测试它,您可以使用下面的代码段。
var s =" [{'id':1,'name':'Test1'},{'id':2,'name':'Test2'}]";
var myObject = eval('(' + s + ')');
for (i in myObject)
{
alert(myObject[i]["name"]);
}
hope it helps..
希望能帮助到你..
回答by Gyanesh Gouraw
As simple as that.
就如此容易。
var str = '{"id":1,"name":"Test1"},{"id":2,"name":"Test2"}';
dataObj = JSON.parse(str);
回答by Luca Matteis
Append extra an [
and ]
to the beginning and end of the string. This will make it an array. Then use eval()
or some safe JSON serializer to serialize the string and make it a real JavaScript datatype.
在字符串的开头和结尾附加额外的[
和]
。这将使它成为一个数组。然后使用eval()
或一些安全的 JSON 序列化器来序列化字符串并使其成为真正的 JavaScript 数据类型。
You should use https://github.com/douglascrockford/JSON-jsinstead of eval()
. eval is only if you're doing some quick debugging/testing.
您应该使用https://github.com/douglascrockford/JSON-js而不是eval()
. eval 仅在您进行一些快速调试/测试时使用。
回答by greenimpala
回答by Steve
I know a lot of people are saying use eval. the eval() js function will call the compiler, and that can offer a series of security risks. It is best to avoid its usage where possible. The parse function offers a more secure alternative.
我知道很多人都在说使用 eval。eval() js 函数会调用编译器,这会带来一系列的安全风险。最好尽可能避免使用它。parse 函数提供了更安全的替代方案。