JSON Tutorial - Learn How to Use JSON with JavaScript

In this tutorial, we’re going to learn about JSON. We will cover JSON structure, different data types and how to use JSON inside JavaScript.

JSON is one of the most important concepts that you can learn as a programmer or as a QA.

Throughout your programming career you’re going to use JSON all the time whether it’s creating an API, consuming an API, or creating config files for your application.

What is JSON

JSON which stands for JavaScript object notation, is simply a data representation format very similar to XML or YAML.

It’s used widely across the internet for almost every single API that you will access, as well as for config files and things such as games and text editors.

An example of a JSON:

#user.json
{
    "name": "Steve",
    "age": 43,
    "isProgrammer" true,
    "hobbies": ["Reading Java books", "cooking", "classic music"],
    "friends": [{
        "name": "joey",
        "age": 39,
        "isProgrammer": false,
        "friends": [...]
    }]
}

Why Use JSON

We use JSON because it’s extremely lightweight to send back and forth in http requests and responses due to the small file size.

It’s easy to read compared to something like XML since it’s much cleaner and there’s not as many opening and closing tags to worry about.

JSON also integrates very nicely with JavaScript since JSON is just a subset of JavaScript, which means anything you write in a JSON is valid JavaScript.

Almost every single major language has some form of library or built-in functionality to parse JSON strings into objects or classes in that language.

This makes working with JSON data extremely easy inside of a programming language.

JSON Data Types

Now that we understand what JSON is and why it’s important, let’s dive into some of the syntax involved and the data types that JSON can represent.

As we know JSON is a data representation format so we need to be able to represent a certain data types within it.

JSON natively supports:

  • strings
  • numbers numbers can be in any format whether they’re decimal numbers whole numbers negative numbers even scientific notation numbers
  • booleans which can be either true or false
  • null which essentially stands for nothing
  • Arrays which can be a list of any of the types above
  • Objects an object is the most complex but most used type within json as it allows you to represent data that are key value pairs

JSON Example

Let’s dive into an example of how to use json inside of a file.

The first thing that you need to do is to create a file with the .json extension at the end of it.

We’re going to create a user.json file with a user object represented as JSON.

To create an object we need to use opening and closing curly braces {} and then inside of that we’ll put all of the key value pairs that make up our object.

Every single property inside the JSON is a key value pair. The key must be surrounded by double "" quotes followed by a colon : and then the value for that key.

If we have multiple key value pairs, we need commas , separating every single one of our key value pairs, similar to how we would create an array in a normal programming language.

Example JSON File

#user.json
{
    "name": "Steve",
    "age": 43,
    "isProgrammer" true,
    "hobbies": ["Reading Java books", "cooking", "classic music"],
    "friends": [{
        "name": "joey",
        "age": 39,
        "isProgrammer": false,
        "friends": [...]
    }]
}

In the above example, we have a file called user.json. Inside the file we have different data types.

The keys are always surrounded by double quotes. For the values, only the string type is surrounded by double quotes.

In the example:

  • name is string
  • age is integer
  • isProgrammer is boolean
  • hobbies is an Array
  • friends is an Array of Objects

How to Use JSON String Inside JavaScript

Let’s assume we have a JSON file called companies.json which is an array of company objects:

[
    {
        "name": "Big corporate",
        "numberOfEmployees": 1000,
        "ceo": "Neil",
        "rating": 3.6
    },
    {
        "name": "Small startup",
        "numberOfEmployees": 10,
        "ceo": null,
        "rating": 4.3
    }
]

In the above example, we have two company objects inside a JSON array.

Now let’s see how we can use the above JSON inside a JavaScript.

In most scenarios, we get a JSON as a string rather than a JSON object. To emulate this, we represent the above JSON as a string inside the JavaScript.

Our html file looks like:

<!DOCTYPE html>
<html>
<head>
    <title>JSON Example</title>
</head>
<body>
  <script type="text/javascript">
    let companies =
    `[
       {
          "name": "Big corporate",
          "numberOfEmployees": 1000,
          "ceo": "Neil",
          "rating": 3.6
        },
        {
          "name": "Small startup",
          "numberOfEmployees": 10,
          "ceo": null,
          "rating": 4.3
       }
    ]`
    console.log(JSON.parse(companies))
    </script>
</body>
</html>

When we inspect the console log in Chrome Developer Tools, the output is similar to what’s shown below:

JSON javascript example

Then we can parse the above JSON by specifying what we want to extract. For example, if we wanted to get the name of the first company in the array we would use:

console.log(JSON.parse(
    companies[0].name
))

Output: Big corporate

Likewise, to get the rating of the second company we would use:

console.log(JSON.parse(
    companies[1].rating
))

Output: 4.3

How to Convert JavaScript Object to JSON

Now suppose we have a JavaScript object like the one shown below:

<html>
<head>
    <title>JSON Example</title>
</head>
<body>
  <script type="text/javascript">
    var person = {
        name: "Brad",
        age: 35
    }
    </script>
</body>
</html>

To convert the person JavaScript object to JSON we use stringify method:

jsonPerson = JSON.stringify(person);

The output is a valid JSON:

{
    "name": "Brad",
    "age": 35
}

To make the above work, we need to convert the JSON back to JavaScript object.

How to Convert JSON Object to JavaScript

To convert the above JSON object back to JavaScript, we use the parse method:

jsPerson = JSON.parse(jsonPerson)

Complete Example

<!DOCTYPE html>
<html>
<head>
    <title>JSON Example</title>
</head>
<body>
  <script type="text/javascript">
    var person = {
        name: "Brad",
        age: 35
    }
    jsonPerson = JSON.stringify(person); //convert to JSON
    console.log(jsonPerson.name); //undefined

    jsPerson = JSON.parse(jsonPerson); //convert to JS Object
    console.log(jsPerson.name); //Brad
    </script>
</body>
</html>

Summary

  • JSON stands for JavaScript Object Notation
  • Lightweight data-interchange format
  • Based on a subset of JavaScript
  • Easy to read and write
  • Language independent
  • Can be parsed in most modern programming languages

Data Types:

  • Number: No difference between integer and float
  • String: String of Unicode characters. Use double quotes
  • Boolean: True or false
  • Array: Ordered list of 0 or more values in []
  • Object: Unordered collection of key/value pairs
  • Null: Empty value

JSON Syntax Rules:

  • Uses key/value pairs - e.g. {"name": "value"}
  • Uses double quotes around KEY
  • Must use the specified data types
  • File type is .json
  • MIME type is “Application/json”

I hope you found this JSON tutorial with Javascript useful. You can now write simple and complex JSON files and interact with JSON strings inside JavaScript.