I have JSON which contains function names:
{
"login": "do_login",
"logout": "do_logout"
}
Is it possible after parsing that JSON to call functions do_login
and do_logout
?
I mean this:
var obj = JSON.parse({"login": "do_login","logout": "do_logout"});
obj.login();
I have JSON which contains function names:
{
"login": "do_login",
"logout": "do_logout"
}
Is it possible after parsing that JSON to call functions do_login
and do_logout
?
I mean this:
var obj = JSON.parse({"login": "do_login","logout": "do_logout"});
obj.login();
Share
Improve this question
edited Dec 14, 2020 at 22:47
Jason Aller
3,65228 gold badges41 silver badges39 bronze badges
asked Oct 22, 2012 at 6:29
rsboarderrsboarder
4,7923 gold badges21 silver badges21 bronze badges
1
- In this case you wouldn't need JSON parse. Where do you get this object from? Is it a string and therefor you want to parse it back? – Chris Commented Oct 22, 2012 at 6:36
3 Answers
Reset to default 9I'm not sure if I understood it correctly but try this
window[obj.login]();
You may be confused about what JSON is. JSON is a string that represents an object. What you have above is known as an object literal.
A JSON string would look like this "{\"login\":\"do_login\",\"logout\":\"do_logout\"}"
This is a mon mistake since both have a similar layout. This is no accident. When Crawford came up with JSON he modeled it on javascript object literals.
Functions are not converted to JSON strings, JSON.stringify will ignore them.
Example:
var foo = {
bar: function() {
console.log('bar');
},
something: 'something'
}
JSON.stringify(foo) // "{\"something\":\"something\"}"
I can run foo.bar() in my code, but this is not JSON it is a JS object.
You could do this:
var obj = function(){};
obj.login = function(){
//login code
};
obj["login"]();//call login function
Here is a better worded example:
var Functions = function(){};
Functions.do_login = function(){
//login code
};
var callbacks = JSON.parse('{"login":"do_login","logout":"do_logout"}');
Functions[callbacks["login"]]();
See a working fiddle to see it in action: http://jsfiddle/hvx7m/2/