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

Posted by Vilx- on Stack Overflow See other posts from Stack Overflow or by Vilx-
Published on 2010-04-19T13:08:43Z Indexed on 2010/04/19 13:13 UTC
Read the original article Hit count: 223

Filed under:
|

JSON is a nice way to pass complex data from my server side code to client side JavaScript. 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?

© Stack Overflow or respective owner

Related posts about JSON

Related posts about standards