JSON in JavaScript

JSON is text, remember? This means that if you somehow get the content of a JSON file into JavaScript, or if you define some JSON object in JavaScript it is just a string value. In order to use it in JavaScript as an object, you must transform it from a string to an object. This is called deserializing, and may, strictly speaking, be done in two ways: with JSON.parse, or with eval. A word of advice, never use the latter, always use JSON.parse. In Crockford's, [Cro08], words, the eval function has horrendous security problems. We showed you an example of JSON.parse a short while ago, here is another:

Example 36.19. JSON String to Object with JSON.parse

let myJsonString = '{ "name": "Aarhus", "population": 340421, "country": "DNK" }';
let myJsonObject = JSON.parse(myJsonString);
document.write("<p>" + myJsonObject.name + ' has ' + myJsonObject.population + ' inhabitants</p>');

Click here!


The opposite of deserialization is (of course) serialization, makes an object into a text string whenever that is necessary. The JavaScript function to do that is very appropriately called JSON.stringify().

Example 36.20. JSON Object to String with JSON.stringify
<!doctype html>
<html>
    <head>
        <meta charset='utf-8'/>
        <title>AJaX</title>
        <script>
            let obj = {
                name: "LS",
                species: "Cat",
                age: 15,
                declawed: false,

                toString() {
                    let s = "";
                    s += `My name is ${obj.name}, I am a ${obj.species}, and I am ${obj.age} years old`;
                    return s;
                }
            }
            
        </script> 
    </head>
    <body>
        <h1>Niels' JSON Demo - Stringify</h1>
        <script>
            document.write("<p>" + obj.toString() + "</p>");
            
            let serializedObj = JSON.stringify(obj);
            document.write("<pre>" + serializedObj + "</pre>");

            serializedObj = JSON.stringify(obj, null, "\t");
            document.write("<pre>" + serializedObj + "</pre>");
        </script>
    </body>
</html>

Click here.

Please notice that, as mentioned earlier, methods are not serialized to JSON text output.