I must convert a string representation of an array of objects returned from AJAX to an array of objects in JavaScript.
我必须将从AJAX返回的对象数组的字符串表示形式转换为JavaScript中的对象数组。
ajaxret = "[{a:'a', b:'b', c: 1},{a:'aa', b:'ab', c: 2},{a:'aaa', b:'bbb', c: 3}]"
strResult = [{a:'a', b:'b', c: 1},{a:'aa', b:'ab', c: 2},{a:'aaa', b:'bbb', c: 3}]
1 个解决方案
#1
1
When you serialize your objects into strings, you should produce valid JSON, using
将对象序列化为字符串时,应使用生成有效的JSON
var string = JSON.stringify(object);
To parse to an object again, then you can use
要再次解析对象,您可以使用
var object = JSON.parse(string);
In your case, since you have invalid JSON, the simple way is
在您的情况下,因为您有无效的JSON,简单的方法是
var object = eval(string);
Warning!!!
警告!!!
-
eval
is evil - eval是邪恶的
- Use it only if the source is completely trusted
- 仅在源完全受信任时使用它
- A malicious source could execute arbitrary code. So bad!
- 恶意源可以执行任意代码。太糟了!
-
JSON.parse
is probably faster - JSON.parse可能更快
#1
1
When you serialize your objects into strings, you should produce valid JSON, using
将对象序列化为字符串时,应使用生成有效的JSON
var string = JSON.stringify(object);
To parse to an object again, then you can use
要再次解析对象,您可以使用
var object = JSON.parse(string);
In your case, since you have invalid JSON, the simple way is
在您的情况下,因为您有无效的JSON,简单的方法是
var object = eval(string);
Warning!!!
警告!!!
-
eval
is evil - eval是邪恶的
- Use it only if the source is completely trusted
- 仅在源完全受信任时使用它
- A malicious source could execute arbitrary code. So bad!
- 恶意源可以执行任意代码。太糟了!
-
JSON.parse
is probably faster - JSON.parse可能更快