由于函数JSON.stringify():
,我有这个JSON{"get":"function (f,g){'use strict';var h,i;if(i={},'string'==typeof f){if('object'==typeof g)for(h in g)i[h]=g[h];i.url=f}else if('object'==typeof f)for(h in f)i[h]=f[h];return i.type=i.type||d,i.oauthio={provider:a,tokens:b,request:c},e.http(i)}","post":"function (f,g){'use strict';var h,i;if(i={},'string'==typeof f){if('object'==typeof g)for(h in g)i[h]=g[h];i.url=f}else if('object'==typeof f)for(h in f)i[h]=f[h];return i.type=i.type||d,i.oauthio={provider:a,tokens:b,request:c},e.http(i)}"}
如何看待值内有函数。我想重建这个JavaScript对象,我的目标是删除risult中的引号以及值;因为在这种情况下,函数被识别为字符串。我想要这样的东西:{key : value}
现在我得到:{key : "value"}
答案 0 :(得分:2)
此解决方案优于使用eval
:
让我们说obj
包含你的json,这意味着函数是obj.get
但它是一个刺痛,将它转换为实函数,你可以使用构造函数Function
obj.get = new Function(obj.get);
请注意,我在您的代码上尝试了它,但您发布的字符串上有一些错误。确保你的功能正确。
答案 1 :(得分:2)
快速回答:
以下功能将执行此操作:
function fix(obj){
for (var property in obj) {
if (obj.hasOwnProperty(property)) {
obj[property] = eval("(" + obj[property] + ")");
}
}
}
如果 obj 包含您的JSON解析对象,则只需执行以下操作:
fix(obj);
console.log(obj); // in case you want to see the change in the console
解释(如果您需要):
如果在调用eval之前用括号'()'括起字符串,你将能够获得javascript函数表达式。
因此,实现预期结果的步骤是:
对于您给出的简单示例,您可以通过以下方式获得所需的结果:
var obj = {"get":"function (f,g){'use strict';var h,i;if(i={},'string'==typeof f){if('object'==typeof g)for(h in g)i[h]=g
[h];i.url=f}else if('object'==typeof f)for(h in f)i[h]=f[h];return i.type=i.type||d,i.oauthio=
{provider:a,tokens:b,request:c},e.http(i)}","post":"function (f,g){'use strict';var h,i;if(i={},'string'==typeof f){if
('object'==typeof g)for(h in g)i[h]=g[h];i.url=f}else if('object'==typeof f)for(h in f)i[h]=f[h];return i.type=i.type||
d,i.oauthio={provider:a,tokens:b,request:c},e.http(i)}"};
obj.get = eval("(" + obj.get + ")");
obj.post = eval("(" + obj.post + ")");
您可以使用以下功能自动执行该操作:
function fix(obj){
for (var property in obj) {
if (obj.hasOwnProperty(property)) {
obj[property] = eval("(" + obj[property] + ")");
}
}
}
您的最终代码应该是:
function fix(obj){
for (var property in obj) {
if (obj.hasOwnProperty(property)) {
obj[property] = eval("(" + obj[property] + ")");
}
}
}
var obj = {"get":"function (f,g){'use strict';var h,i;if(i={},'string'==typeof f){if('object'==typeof g)for(h in g)i[h]=g
[h];i.url=f}else if('object'==typeof f)for(h in f)i[h]=f[h];return i.type=i.type||d,i.oauthio=
{provider:a,tokens:b,request:c},e.http(i)}","post":"function (f,g){'use strict';var h,i;if(i={},'string'==typeof f){if
('object'==typeof g)for(h in g)i[h]=g[h];i.url=f}else if('object'==typeof f)for(h in f)i[h]=f[h];return i.type=i.type||
d,i.oauthio={provider:a,tokens:b,request:c},e.http(i)}"};
fix(obj);
脚注:
如果您有兴趣知道为什么需要括号,请查看以下链接:
Why does JavaScript's eval need parentheses to eval JSON data?