• Calculating...
  • 5 years ago
  • 3.2K Views
  • Archived This is an Archived post.
    The content within this may not be used or replaced with newer versions.

JSON in JavaScript

This tutorial is created to provide you with an introduction to working with JSON (JavaScript Object Notation) in JavaScript. JSON is mostly used with AJAX (Asynchronous JavaScript) and XML. It’s a lightweight format to serialize and transmit structured data over a network connection.

 

JSON for JavaScript is generally used in some of the following scenarios :

  • Data Storage (Storing Data).
  • Data Analysis
  • Data transfer from user / server to relevant medium.
JSON
  • Keys and Values

JSON consist of two primary parts as key and value. Together they make a key/value pair.

  1. Key : It’s always a string enclosed in quotation marks.
  2. Value : It can be a string, number, boolean expression, array, or object.
  3. Key/Value Pair : It follows a specific syntax, with the key followed by a colon followed by the value. Key/value pairs are comma separated.

 

Syntax & Structure

 
{ "key": "value" }
 

JSON array consist of many data types. Here is an example of an array with different data type:

[
    "Bishrul",            // string
    {                     // object
      "id": "01",
      "name": "BH"
    },
    True,                // Boolean
    5.7                  // number
]
 

 

The following data types can be used with JSON:

  • Strings (in double quotes)
  • Arrays
  • Numbers
  • Objects
  • Booleans (true or false)
  • null

Working with JSON in JavaScript

Here’s the JSON data we’ll use in this example:

{
  "details" : [
    {
      "name" : "Bishrul Haq",
      "born" : "1994"
      },
    {
      "name" : "Bill Gates",
      "born" : "1955"
      },
    {
      "name" : "Dennis Ritchie",
      "born" : "1941"
      },
  ]
}
 

In this step, We’ll use JavaScript to take the above JSON data and output it to the HTML document as shown below :

<!doctype html>
<title>JSON Sample | BH</title>
<script>
    function displaydetails() {
        // JSON Details
        let data =
            {
                "details": [
                    {
                        "name": "Bishrul Haq",
                        "born": "1994"
                    },
                    {
                        "name": "Bill Gates",
                        "born": "1955"
                    },
                    {
                        "name": "Dennis Ritchie",
                        "born": "1941"
                    },
                ]
            }

        let output = "<h1>Detaills</h1>";
        output += "<ul>";

        // Loop through the artists
        for (let i in data.details) {
            output += "<li>" + data.details[i].name + " (Born: " + data.details[i].born + ")</li>";
        }

        output += "</ul>";
        document.getElementById("detailList").innerHTML = output;
    }

    window.onload = displaydetails;
</script>

<!-- output -->
<div id="detailList"></div>
 
  • Convert a JavaScript object into a String

The JSON.stringify() function converts JS object into a string. Strings are lightweight and it’s faster to use between client to server.

Let’s assign the JSON.stringify() method to following variable output.

<!doctype html>
<title>JSON Sample | BH</title>
<script>
    function displaydetails() {
        // JSON Details
        let data =
            {
                "details": [
                    {
                        "name": "Bishrul Haq",
                        "born": "1994"
                    },
                    {
                        "name": "Bill Gates",
                        "born": "1955"
                    },
                    {
                        "name": "Dennis Ritchie",
                        "born": "1941"
                    },
                ]
            }

        let output = JSON.stringify(data);
        document.getElementById("detailList").innerHTML = output;
    }

    window.onload = displaydetails;
</script>

<!-- output -->
<div id="detailList"></div>
 
 

To convert a JSON String back into a function, We use JSON.parse() function.It helps to access the data like a regular JavaScript object.

let output = JSON.parse(output);
 
  • Nested JSON Objects

In this Step, We’ll use a JSON file with Deeper Nesting. Not only does this file have details about users, but each user has a number of skills. So we need to loop through the users, and also loop through each users’ skills.

<!doctype html>
<title>JSON Example | BH</title>
<script>
    function displayUsers() {
        // JSON data
        let data =
            {
                "users": [
                    {
                        "name": "Jhon",
                        "born": "1994",
                        "skills": [
                            {
                                "skillname": "Java Programming",
                                "experience": "2 Years"
                            },
                            {
                                "skillname": "Laravel",
                                "experience": "1 Years"
                            },
                            {
                                "skillname": "React Native",
                                "experience": "3 Years"
                            }
                        ]
                    }, {
                        "name": "Bishrul Haq",
                        "born": "1994",
                        "skills": [
                            {
                                "skillname": "Android Development",
                                "experience": "2 Years"
                            },
                            {
                                "skillname": "Angular JS",
                                "experience": "1 Years"
                            }
                        ]
                    },
                ]
            };

        let output = "<h1>Users</h1>";

        // Loop through the users
        for (let i in data.users) {
            output += "<h2>" + data.users[i].name + "</h2>";
            output += "<ul>";

            // Loop through the user for their skills
            for (let j in data.users[i].skills) {
                output += "<li>" + data.users[i].skills[j].skillname;
            }
            output += "</ul>";
        }
        document.getElementById("usersList").innerHTML = output;
    }

    window.onload = displayUsers;
</script>

<!-- Output -->
<div id="usersList"></div>
 

Hope this tutorial helped you! Feel free to drop your opinion at the comment section.

Share:

Related Post

How to Get, Set and Delete Div Background Image using jQuery?

This tutorial is created to Set, Get and Delete background image. In this tutorial, You’ll learn to Get, Set and Remove the background image using jQuery.

  • 5 years ago

AJAX for Database Operations

This tutorial is created to implement CRUD operations via AJAX (Asynchronous JavaScript and XML). Ajax is used for rich-internet applications that emulate the responsiveness and complex user interface

  • 5 years ago