开发者

Is using advanced constructs (function, new, function calls) in JSON safe?

JSON is a nice way to pass complex data from my server side code to client side Ja开发者_如何学CvaScript. For example, in PHP I can write:

<script type="text/javascript>
    var MyComplexVariable = <?= BigFancyObjectGraph.GetJSON() ?>;
    DoMagic(MyComplexVariable);
</script>

This is pretty cool, but sometimes you want to pass more than basic date, like dates or even function definitions. There is a simple and straightforward way of doing it too, like:

<script type="text/javascript>
    var MyComplexVariable = {
        'SimpleProperty' : 42,
        'FunctionProperty' : function()
         {
             return 6*7;
         },
         'DateProperty' : new Date(989539200000),
         'ArbitraryProperty' : GetTheMeaningOfLifeUniverseAndEverything()
    };
    DoMagic(MyComplexVariable);
</script>

And this works like a charm on all browsers I've seen so far. But according to JSON.org such syntax is invalid. On the other hand, I've seen this syntax being used in very many places, including some popular JavaScript frameworks. So...

Can I expect any problems if I use "unsupported" JSON features like the above? Why is it wrong or not?

Added clarification: If I expected my JSON to be consumed by some unknown 3rd party software, or even a known parser which was not a browser, then such exotics would indeed most likely not work and I would not attempt to embed them. But I'm interested in the case where the JSON code is written directly inside a JavaScript code block that is executed by an Internet browser. Like the examples above.


According to JSON.org, a JSON object only supports the following value members of an object:

Is using advanced constructs (function, new, function calls) in JSON safe?


(source: json.org)

Since none of these is a function, I would suggest not using it since, as you said, it is not officially supported in the spec.

Besides, what happens when a non-Javascript client (such as a Python program) tries to consume your JSON? How is it going to run your JavaScript code?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜