QUICK ANSWER:
Here is a function that can achieve the desired outcome:
function fixObject(obj){
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
obj[prop] = eval("(" + obj[prop] + ")");
}
}
}
If your JSON parsed object is named obj, simply call the function like this:
fixObject(obj);
console.log(obj); // this will show the changes in the console
EXPLANATION (IF YOU NEED ONE):
By enclosing the string in parentheses before using eval, you can obtain the javascript function expression.
The steps to achieve this are:
- Enclose the function expression string in parentheses
- Evaluate the function declaration expression using eval
- Assign the function declaration expression to the same property initially containing the string value
For the example provided, you can proceed as follows:
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 the process with this function:
function fixObject(obj){
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
obj[prop] = eval("(" + obj[prop] + ")");
}
}
}
Your final code should look something like this:
function fixObject(obj){
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
obj[prop] = eval("(" + obj[prop] + ")");
}
}
}
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)}"
};
fixObject(obj);
Footnotes:
If you are curious about the need for parentheses in eval, you can read more about it here.