JSON

7 0 0
                                        

JSON or JavaScript Object Notation - It works like a static class in Java. An example of a static class is the Math class. Why static? It is because there is no need to create an object just to access the methods and properties of the class. This JSON is possible to be a class that handles the Standard String formatting for Javascript objects keys and values.

In Java, accessing PI = 3.14 is like this: Math.PI

In JSON, accessing the predefined function is like

    1. JSON.stringify(object) - this converts the object to JSON string format.

    2. JSON.parse(string) - this converts the JSON string format to object.

======================

let book = {

    title: "Reincarnated as a Slime",

    author: "Rimuru Senpai",

    published: 2021

};

let str1 = JSON.stringify(book);

function getJsonString(){

    document.writeln(str1);

}

let obj = JSON.parse(str1);

function convertingJsonToObject(){

    for(let x in obj)

        document.writeln(obj[x]);

}

=====================

HTML

<h2>

    <script>

        getJsonString()

    </script>

    <br />

</h2>

<h4>

    <script>

        convertingJsonToObject()

    </script>

    <br />

</h4>

Result:

{"title":"Reincarnated as a Slime","author":"Rimuru Senpai","published":2021}

Reincarnated as a Slime Rimuru Senpai 2021

Note:  About the results...

1. The top is the JSON string format of an object. This is the result when we converted the object to JSON format string. 

2. The second is the value of each object key iterated from an object. This is the result when we converted the JSON format string to object. So, we iterate each value because it is an object.

3. JSON formatting ignores functions, Symbols and undefined properties but it does include nested objects.

    1. JSON.stringify(object, [replacer, space]) - this methods has two optional parameters that is useful. The replacer argument is an array of keys that you want to customize to include in your function. The space is for the spacing of the JSON format strings.

    let str1 = JSON.stringify(book, ["title", "author", "published"], 2);

2. JSON.parse(string, [reviver]) - this method has an optional parameter too. Reviver is a function that has access to each member of an object.

3. toJson() - It works like a toString(). If the object has toJSON() function, then this notifies the JSON object to include it in the formatting.

===============

let libraryId = {

    id: 1000,

    toJSON(){

        return this.id;

    }

};

================

Javascript ProgrammingWhere stories live. Discover now