[英]How can I convert the string of a JavaScript object literal to a JavaScript object literal?
How can I convert the string... 我如何转换字符串...
"{ name: 'John' }"
...to an actual JavaScript object literal that will allow me to access the data using its keys (Ie varname["name"] == "John")? ...到一个实际的JavaScript对象文字,该文字将允许我使用其键(即varname [“ name”] ==“ John”)访问数据? I can't use JSON.parse(), since the string is invalid JSON.
我不能使用JSON.parse(),因为字符串是无效的JSON。
You could use eval(). 您可以使用eval()。
var str = "{ name: 'John' }";
var obj = eval("(" + str + ")");
From the previous question 来自上一个问题
s="{ name: 'John'}";
eval('x='+s);
Example with new Function
new Function
示例
var str = "{ name: 'John' }"; var fnc = new Function( "return " + str ); var obj = fnc(); console.log(obj.name);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.