I'm retrieving an array of objects from a hidden html input field. The string I'm getting is:
我正在从隐藏的html输入字段中检索一个对象数组。我得到的字符串是:
"{"id":"1234","name":"john smith","email":"jsmith@blah.com"},{"id":"4431","name":"marry doe","email":"mdoe@blah.com"}"
Now I need to pass this as an array of objects again. How do I convert this string into array of objects?
现在我需要再次将其作为一个对象数组传递。如何将此字符串转换为对象数组?
3 个解决方案
#1
12
var array_of_objects = eval("[" + my_string + "]");
This executes the string as code, which is why we need to add the [] to make it an object. This is also one of the few legitimate uses for eval as its the fastest and easiest way. :D
这会将字符串作为代码执行,这就是我们需要添加[]以使其成为对象的原因。这也是eval作为最快和最简单方法的少数合法用途之一。 :d
#2
7
Assuming that str
holds valid JSON syntax, you can simply call eval(str)
.
假设str保存有效的JSON语法,您只需调用eval(str)即可。
For security reasons, it's better to use a JSON parser, like this:
出于安全原因,最好使用JSON解析器,如下所示:
JSON.parse(str);
Note that str
must be wrapped in []
to be a valid JSON array.
请注意,str必须包含在[]中才能成为有效的JSON数组。
#3
0
var str=eval([{'id':'1','txt':'name1'},{'id':'2','txt':'name2'},{'id':'3','txt':'name3'}])
for(var i=0;i<str.length;i++)
{
alert(str[i].txt);
}
#1
12
var array_of_objects = eval("[" + my_string + "]");
This executes the string as code, which is why we need to add the [] to make it an object. This is also one of the few legitimate uses for eval as its the fastest and easiest way. :D
这会将字符串作为代码执行,这就是我们需要添加[]以使其成为对象的原因。这也是eval作为最快和最简单方法的少数合法用途之一。 :d
#2
7
Assuming that str
holds valid JSON syntax, you can simply call eval(str)
.
假设str保存有效的JSON语法,您只需调用eval(str)即可。
For security reasons, it's better to use a JSON parser, like this:
出于安全原因,最好使用JSON解析器,如下所示:
JSON.parse(str);
Note that str
must be wrapped in []
to be a valid JSON array.
请注意,str必须包含在[]中才能成为有效的JSON数组。
#3
0
var str=eval([{'id':'1','txt':'name1'},{'id':'2','txt':'name2'},{'id':'3','txt':'name3'}])
for(var i=0;i<str.length;i++)
{
alert(str[i].txt);
}