Working with JSON

Lord AbiollaLord Abiolla
6 min read

Introduction to JSON

JSON (JavaScript Object Notation) is a light-weight data interchange format that is used for storing and transferring data between a server and a client.

Its simplicity, readability, and compatibility with various programming languages make it a go-to choice for data exchange, configuration, and storage. It’s also easy for humans to read and machines (computers) to parse and generate.

With a file extension of .json, JSON is based on JavaScript object syntax but it’s language independent.

JSON Structure and Syntax

JSON is composed of key-value pairs which are enclosed in curly braces{} to form an object. Each key within the object is followed by a colon : and the corresponding value, and multiple key - value pairs are separated by a comma.

Example

{
    "name": "Lord Abiolla",
    "age": 30,
    "isStudent": true
}

In the above examples, “name”, “age”, and “isStudent” are the keys while “Lord Abiolla”, 30, and true are the corresponding key values.

The keys must always be inside double quotes and the value can be a string, integer, boolean, array, object, or null.

Example

{
  "name": "Lord Abiolla",
  "age": 20,
  "isStudent": false,
  "courses": ["Math", "Science", "History"]
}

JSON objects can also be nested within each other, allowing for complex data structures as shown below;

{
  "name": "Lord Abiolla",
  "age": 20,
  "isStudent": false,
  "address": {
    "city": "Nairobi",
    "country": "Kenya",
    "continent": "Africa"
  }
}

Here we can a value associated with “address” key being passed as another JSON object.

JSON vs JavaScript Object

Although JSON looks like a JavaScript object, they are not the same thing.

Let’s look at some of the differences between these two:

FeatureJSONJavaScript Object
1. Quotes around keysMandatory double quotes around keysOptional quotes (if valid identifier)
2. String quotesMust use double quotes on string.Can use single or double quotes on string.
3. Values allowedAllow string, numbers, boolean, null, object, arrayCan include functions, undefined, symbols, etc.
4. CommentsDoes not allow comments in between the data.Comments are allowed in code.
5. Datatype strictnessStrict JSON rulesFlexible JavaScript syntax
6. ExecutionIt’s just data (No code execution)Can contain methods and executable code.

Example of a valid JSON

{
  "id": 101,
  "name": "Lord",
  "address": {
    "street": "123 Main St",
    "city": "Nairobi",
    "country": "Kenya"
  },
  "orders": [
    { "id": 1, "product": "Laptop", "price": 1200 },
    { "id": 2, "product": "Phone", "price": 800 }
  ]
}

Example of JavaScript Object (Invalid JSON)

let data = {
  id: 101,
  name: 'James',
  address: {
            street: '123 Main St',
            city: 'Nairobi'
            },
  orders: [
    {
        id: 1,
        product: 'Laptop',
        price: 1200
    }
  ]
};

Working with JSON in JavaScript

Since JSON is a data interchange and language-independent, every language has a way of dealing with JSON data. In JavaScript, to use JSON, we have to convert it to JavaScript object and vice verse.

To do this, two main methods are of importance here;

  • The JSON.stringify() method

  • The JSON.parse() method

  1. The JSON.stringify() method

JSON.stringify() is a method that is used to convert a JavaScript Object to a JSON string. This method works under the hood to automatically handle nested objects and arrays.

The JSON.stringify() method takes one argument which is the JavaScript object to be converted to a JSON string.

For example

let student = {
    name: 'Lord',
    age: 25,
    isStudent: true
}

let studentJSON = JSON.stringify(student);
console.log(studentJSON);

We can see from the output below that the keys have double quotes as well as the string ‘Lord"‘ which had a single quote has been converted to have double quotes, to fulfill the JSON rule

The JSON.parse() method

JSON.parse() is a method that is used to convert a JSON string back to a JavaScript object.

It also takes one argument which is the JSON string to be converted into a JavaScript object.

Once JSON string has been converted to a JavaScript object, we can use JavaScript object’s way of accessing the data (dot notation and bracket notation) to access the values of every key.

For example

let studentJSON = '{"name": "Lord","age": 25,"isStudent": true}';

let studentObj = JSON.parse(studentJSON);
console.log(studentObj.name); //Lord

We can see from the output below ‘Lord’ being printed as a string. we have used the dot notation to get the value of ‘name’ and printed it to the console.

Also note how the JSON data above has been formatted in a line with the curly braces being inside a single quote.

JSON in Web Storage

Both localStorage and sessionStorage can only store data as strings. Meaning if you try to store a JavaScript object or array directly, it will not work as expected because they will be converted to something meaningless like "[object Object]".

Therefore, to store a JavaScript Object in web storage, we have to convert the object in to JSON string using the JSON.stringify() method.

When retrieving data from web storage, in order to use it as a JavaScript Object, we again convert it to JavaScript Object using the JSON.parse() which converts the JSON string to JavaScript Object.

Below is an example that stores data in localStorage and also retrieves the data. It first converts the JavaScript Object to a JSON string and stores it into the localStorage. When retrieved, the JSON string is converted back to JavaScript Object.

// 1. Create a JavaScript Object

let settings = {
    theme: 'dark',
    fontSize: 14
}

// 2. Convert to JSON string before storing
localStorage.setItem("settings", JSON.stringify(settings));

// 3. Retrieve stored data
let storedValue = localStorage.getItem("settings");
console.log(storedValue);

// 4. Convert to JavaScript Object
let storedValueObj = JSON.parse(storedValue);
console.log(storedValueObj.theme); // Output: dark
console.log(storedValueObj.fontSize); // Output: 14
  • Always remember to stringify your object or array before storing to the web storage.

  • Always parse after receiving data from the storage because if you forget to pass, it will be assumed you’re trying to work with a string instead of structured data.

  • Both localStorage and sessionStorage work exactly the same way for JSON — the only difference is their data persistence.

Fetching JSON data from a server

When we fetch data from a server in modern JavaScript, it is often sent in JSON format.
However, when data arrives, it comes as raw text — so we still need to parse it before using it like a normal JavaScript object.

The Fetch API is the modern way to make HTTP requests in JavaScript.
Here’s how it works step-by-step:

fetch("https://api.example.com/users")
    .then(response => {
        return response.json();
    })
    .then(data => {
        console.log(data);
        console.log(data[0].name);
    })
    .catch(error => {
        console.error("Error: ", error);
    });

In the above code, fetch() sends a request and returns a Promise containing a Response object. The Response object has a .json() method that reads the body of the response and parses it into a JavaScript object.

The second .then() gets the parsed data so you can use it normally. We have a .catch() at the end that detects errors such as ‘no internet connection’ or ‘invalid URL’ and logs it.

For example, if the API returns a JSON like [{“name”: “Lord”, “age”: 24}, {“name”: “Abiolla”, “age”: 22}]. After parsing, data becomes a normal JavaScript array of objects so you can log them as shown below.

console.log(data[1].age);

Conclusion

JSON is a bridge that allows different systems and applications to communicate reliably, ensuring that data remains structured. consistent, and easy to manipulate.

Mastering JSON is an essential step for anyone building interactive, data-driven applications.

0
Subscribe to my newsletter

Read articles from Lord Abiolla directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Lord Abiolla
Lord Abiolla

Passionate Software Developer with a strong enthusiasm for data, technology, and entrepreneurship to solve real-world problems. I enjoy building innovative digital solutions and currently exploring new advancements in data, and leveraging my skills to create impactful software solutions. Beyond coding, I have a keen interest in strategic thinking in business and meeting new people to exchange ideas and collaborate on exciting projects.