JSON.parse() Method: How to parse JSON in JavaScript?

Are you wondering how to parse JSON using JSON.parse() method in JavaScript?

Explore the world of JSON, a language-independent data format that’s essential for sending data from a server to a web page.

This comprehensive guide covers everything from the basics of JSON and its syntax to how to parse JSON in JavaScript using the JSON.parse() method.

With numerous examples and clear explanations, you’ll learn how to handle different data types, nested JSON, and even use a reviver function.

But before that, let us first understand what is JSON.

What is JSON?

JSON, stands for JavaScript Object Notation, is a way to store information in an organized and easy-to-access manner. It gives us a human-readable collection of data that we can access in a logical way.

In a nutshell, it gives us a human-readable collection of data that we can access in a really logical manner. It’s a language-independent data format.

It was inspired by the object literals of JavaScript, but as many other languages have similar features, it’s pretty much universal.

JSON is often used when data is sent from a server to a web page. It’s “self-describing” and easy to understand.

The JSON format is essentially a string representation of a JavaScript object. Because of this similarity, JavaScript programs can easily convert JSON data into JavaScript objects.

Here’s an example of what JSON might look like:

{
"Students": [
{"firstName":"It", "lastName":"Sourcecode"},
{"firstName":"Source", "lastName":"Code"},
{"firstName":"Code", "lastName":"Itsource"}
]
}

As you can see, an object named “Students” is defined as an array containing three objects. Each object represents a person and has properties for first name and last name.

What is JSON.parse() method in JavaScript?

The JSON.parse() method in JavaScript is a built-in method that takes a JSON string as input and converts it into a JavaScript object or value.

Syntax

JSON.parse(text)

JSON.parse(text, reviver)

In the above syntax, text is the JSON string that you want to convert into a JavaScript object or value.

Parameter

text (required)

Text is a string to parse as JSON. This string must be written in JSON format, or else a SyntaxError will be thrown.

reviver (optional)

A function that alters the behavior of the string-to-object conversion process. If a function is provided, it will be called for each item in the object or array being parsed.

Return value

The JSON.parse() method returns the Object, Array, string, number, boolean, or null value corresponding to the given JSON text.

Exceptions

SyntaxError 

A SyntaxError will be thrown if the string to be parsed is not written in a valid JSON format.

How to parse JSON in JavaScript?

You can parse JSON using the JSON.parse() method in JavaScript.

Here’s an example:

let json = '{"name":"Itsourcecode", "age":18, "city":"USA"}';
let obj = JSON.parse(json);
console.log(obj.name); 
console.log(obj.age); 
console.log(obj.city); 

In this example, JSON.parse() method is used to convert a JSON string into a JavaScript object.

Then you can use this object and access its properties like a regular JavaScript object.

Output:

Itsourcecode
18
USA

📌 Please note that the JSON string must be text that follows the JSON syntax rules.

If the string does not follow these rules, JSON.parse() will throw an error.

Here are some examples of how you can use JSON.parse():

JSON.parse("{}"); // returns an empty object: {}

JSON.parse("true"); // returns a boolean: true

JSON.parse('"foo"'); // returns a string: "foo"

JSON.parse('[1, 5, "false"]'); // returns an array: [1, 5, "false"]

JSON.parse("null"); // returns null

And here’s an example of how you can use the reviver parameter:

// Define the JSON string
let jsonString = '{"p": 20}';

// Parse the JSON string, multiplying any numbers by 2
let jsonObject = JSON.parse(jsonString, (key, value) => typeof value === "number" ? value * 5 : value);

// Log the resulting object to the console
console.log(jsonObject);  

In this example, if the value is a number, it’s multiplied by 5 before being returned.

Output:

{ p: 100 }

Examples of parsing JSON in JavaScript?

Here are a few more examples of parsing JSON in JavaScript

Example 1: Parsing an Array

let json = '["English", "Math", "Programming"]';
let samplearray = JSON.parse(json); ✅
console.log(samplearray[0]); 

Output:

English

Example 2: Parsing a Nested JSON

let json = '{"students":{"name":"Itsourcecode", "age":18, "city":"USA"}}';
let obj = JSON.parse(json); ✅
console.log(obj.students.name); 

Output:

Itsourcecode

Example 3: Using a Reviver Function

A reviver function is a function that you can pass as the second argument to JSON.parse() to transform the result:

let json = '{"Fullname":"Itsourcecode", "age":18, "city":"USA"}';
let obj = JSON.parse(json, (key, value) => ✅  {
  if (key === "Fullname") {
    return value.toUpperCase();
  } else {
    return value;
  }
});
console.log(obj);  

In this example, the reviver function transforms the name property to uppercase. The function is called for each item in the JSON.

Conclusion

In conclusion, JSON (JavaScript Object Notation) is used for storing and transferring data in a format that’s both human-readable and easy to parse programmatically.

The built-in JSON.parse() method allows developers to convert JSON strings into JavaScript objects or values, enabling efficient data manipulation.

With the provided examples, you should now have a solid understanding of how to parse various JSON structures in JavaScript, handle potential errors, and even use a reviver function to transform the results.

We are hoping that this article provides you with enough information that help you understand how to parse JSON in JavaScript.

If you want to dive into more JavaScript topics, check out the following articles:

Thank you for reading Itsourcecoders 😊.

Leave a Comment