tags:

views:

15

answers:

1

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?

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.

+2  A: 

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

alt text

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?

Justin Ethier
If I used it just for data where the target parser would most likely NOT be a browser, then I'd agree with you. But I'm asking about the scenario where I'm embedding the JavaScript directly in my JavaScript client side code. It will be executed by a browser.
Vilx-