Parse Function Inside Json
Solution 1:
QUICK ANSWER:
The function bellow will do it:
function fix(obj){
for (var propertyin obj) {
if (obj.hasOwnProperty(property)) {
obj[property] = eval("(" + obj[property] + ")");
}
}
}
If obj has your JSON parsed object then just do the following:
fix(obj);
console.log(obj); // in case you want to see the change in the console
EXPLANATION (IF YOU NEED ONE):
You will be able to get the javascript function expression if you enclose the string with parentheses '()' before invoking eval.
So the steps to achieve the desired result are:
- Enclose the function expression string in parentheses (see footnotes for the reason why)
- Invoke the eval function to evaluate the function declaration expression
- Assign the function declaration expression to the same property that contained the string value
For the simplistic example you gave, you can get the desired results by:
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 + ")");
You can automate that by using the following function:
function fix(obj){
for (var propertyin obj) {
if (obj.hasOwnProperty(property)) {
obj[property] = eval("(" + obj[property] + ")");
}
}
}
Your final code should be something like:
functionfix(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);
Footnotes:
In case you have interest to know why the parentheses are needed please check the link below:
Why does JavaScript's eval need parentheses to eval JSON data?
Solution 2:
this solution is better than using eval
:
let's say obj
contains your json, which means the function is obj.get
but it is a sting, to convert it to a real function, you can use the constructor Function
obj.get = newFunction(obj.get);
Note that I tried it on your code but the string you have posted has some errors on it. make sure your function is correct.
Post a Comment for "Parse Function Inside Json"