JSON Introduction: Learning the Basics of JSON

JSON Introduction: Learning the Basics of JSON

What is JSON?

Javascript Object Notation(JSON) is a lightweight, text-based data interchange format. JSON is used to send data between a client(web browser) and a server over the web.

When a client sends data to a server, the data is sent in a JSON format as a part of the HTTP request. The server receives, processes and extracts this data and performs various actions on the data, such as sending a response to the client or querying a database.

The server performs these actions through a process named Parsing. Parsing involves analyzing the data and breaking it into simpler parts to enable the server to understand and extract the relevant information from this data and respond correctly to the request.

Why Use JSON?

  • Lightweight: JSON data is minute compared to other data interchange formats, making it more efficient to transmit over the web and increasing its processing time.

  • Readability: JSON is easy to use, understand and write and is, therefore, a good choice for data exchange.

  • Universal compatibility: JSON is a widely supported data interchange format often used by many programming languages. It is also language-independent.

  • Usability: JSON supports various data types, including strings, numbers, booleans, arrays, and objects, making it a suitable format for representing different data types.JSON can also be parsed and handled easily within JavaScript code, making it a good choice for applications that use JavaScript.

JSON In Action

JSON is based on javascript object literals and supports any javascript data type. Some of the data types include numbers, booleans, strings, etc. JSON is structured as key/value pairs, with the keys enclosed in double quotes and the JSON data wrapped in a curly brace as shown below:

{
   "name": "Henry",
    "age": 90,
    "isImmortal":true,
    "hobbies": ["going to the gym"]
}
// JSON object containing the information of a user.

JSON Methods

Below are some of the commonly used JSON methods:

  • JSON.parse(): This method converts a JSON string to a javascript object. When receiving data from a web server, the data is always a string. This method accepts a JSON string as an input and returns a javascript object.

       {
        "name": "Iyanu",
        "age": 28,
        "city": "Obalende"
      }
      // Info of a user as a JSON data
    

    By calling the JSON.parse() method on the JSON string, the string is converted to a javascript object and can be used in our application, like so:

      let person = JSON.parse(
          '{"name":"Iyanu","age":28,"city":"Obalende"}'
      );
      console.log(person.name); // "Iyanu"
      console.log(person.age); // 28
      console.log(person.city); // "Obalende"
    

    JSON.parse() with a reviver function:

    This method is similar to JSON.parse() but allows you to modify the returning object during parsing. When you pass a reviver function as the second parameter to JSON.parse(), the function is called for each key-value pair in the JSON string. To know more above Reviver functions, check this resource: Revive your JSON

      const data = '{"name": "jane okafor", "age": 25, "city": "festac"}';
    
      const obj = JSON.parse(data, (key, value) => {
        if (typeof value === 'string') {
          return value.toUpperCase();
        }
        return value;
      });
    
      console.log(obj);
      // {
      //  name: "JANE OKAFOR",
      //  age: 25,
      //  city: "FESTAC"
      // }
    

    In the example above, the data variable contains a JSON string with a user's name, age, and city. The JSON.parse() method is called with a reviver function that checks whether the value of the data is a string, and if found to be true, it converts the value to uppercase using the toUpperCase() method. The result is logged into the console.

  • JSON.stringify(): This method converts a javascript object to a JSON string. This method is used when sending data to a server or an API in JSON format.

let person = {
  name: "Usman",
  age: 18,
  city: "Zaria"
};
// javascript object containing user info

By calling the JSON.stringify() method on the JSON object, the javascript object is converted to a JSON string like so:

let json = JSON.stringify(person);
console.log(json); // '{"name":"Usman","age":18,"city":"Zaria"}'

You can also use the JSON.stringify() method with a Replacer function

const person = {
  name: "usman",
  age: 18,
  city: "zaria"
};

const jsonString = JSON.stringify(person, (key, value) => {
  if (key === "name") {
    return value.toUpperCase();
  }
  return value;
});

console.log(jsonString); // output: {"name":"USMAN","age":18,"city":"zaria"}

In the code above, the person object contains three properties: name, age, and city. The JSON.stringify() method converts this object into a JSON string, with the replacer function received as a second argument to JSON.stringify().

The replacer function receives two arguments: key and value. The function checks if the key is "name" and returns the value in uppercase when true. Otherwise, the code returns the original value.

As a result, the output of JSON.stringify() will have the "name" property in uppercase, while the other properties remain the same.

Conclusion

In conclusion, JSON is a versatile and widely used data format that allows easy and efficient data transfer between applications. Its simple syntax and compatibility with many programming languages make it a popular choice for web development. Whether you're working with front-end or back-end technologies, understanding how to use JSON enhances your development capabilities.

Thank you for staying till the end, and happy coding!👍