Is it valid to define functions in JSON results?

后端 未结 11 754
一向
一向 2020-11-22 11:38

Part of a website\'s JSON response had this (... added for context):

{..., now:function(){return(new Date).getTime()}, ...}

Is adding anony

11条回答
  •  盖世英雄少女心
    2020-11-22 12:11

    A short answer is NO...

    JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.

    Look at the reason why:

    When exchanging data between a browser and a server, the data can only be text.

    JSON is text, and we can convert any JavaScript object into JSON, and send JSON to the server.

    We can also convert any JSON received from the server into JavaScript objects.

    This way we can work with the data as JavaScript objects, with no complicated parsing and translations.

    But wait...

    There is still ways to store your function, it's widely not recommended to that, but still possible:

    We said, you can save a string... how about converting your function to a string then?

    const data = {func: '()=>"a FUNC"'};
    

    Then you can stringify data using JSON.stringify(data) and then using JSON.parse to parse it (if this step needed)...

    And eval to execute a string function (before doing that, just let you know using eval widely not recommended):

    eval(data.func)(); //return "a FUNC"
    

提交回复
热议问题