javascript - Functions in JSON - Stack Overflow

I have JSON which contains function names:{"login": "do_login","logout":

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
Add a ment  | 

3 Answers 3

Reset to default 9

I'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/

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745360253a4624326.html

相关推荐

  • javascript - Functions in JSON - Stack Overflow

    I have JSON which contains function names:{"login": "do_login","logout":

    4小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信