Table of contents
1.
Introduction
2.
JSON Syntax
3.
JSON.parse()
3.1.
Syntax
3.2.
Return Value
3.3.
Exceptions
4.
Using the Optional Reviver Argument
5.
Examples and Exceptions
6.
Frequently Asked Questions
7.
Key Takeaways
Last Updated: Mar 27, 2024

JSON.parse() Method

Author Gunjeev Singh
1 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Javascript Object Notation is a standardized file format used for data interchange between services, programs, and users. The JSON object in Javascript contains methods for resolving JSON and converting values to JSON formats. JSON is a light and efficient way of transferring and storing data. It is the most used format in web services and server-client interactions.

To simplify the concept of JSON, it is merely a syntax for serializing objects, arrays, numbers, strings, booleans, and NULL. In this blog, we will look into the first of the two methods in the JSON object of the Javascript Engine. 

 

You can head to this guided path prepared specially for Javascript beginners to learn more about Javascript. 

JSON Syntax

Before we start learning about the JSON.parse() method, let us understand the basic syntax of JSON. There are a few rules of the JSON method which can be summed up like:

  • The data is always kept in name and value pairs
  • Commas must separate all data
  • Objects are held by curly braces, while square brackets have arrays.

A sample JSON object could be:

{
"students":[
{"firstName":"John", "lastName":"Appleseed"},
{"firstName":"Anna", "lastName":"Jones"},
{"firstName":"Pete", "lastName":"Smith"}
]
}
You can also try this code with Online Javascript Compiler
Run Code

In the above example, "students" is an array of three objects. Shown above is the basic JSON syntax. JSON syntax becomes vital to learn since JSON is the preferred way of transferring data between web applications and servers. 

JSON.parse()

The JSON.parse() method converts a string to a JSON object. It constructs the Javascript value or object which is described in the string. The JSON.parse() method also has an optional parameter, called the reviver. 

Syntax

The syntax of the JSON parsing method is as follows. 

JSON.parse(text)
You can also try this code with Online Javascript Compiler
Run Code
JSON.parse(text, reviver)
You can also try this code with Online Javascript Compiler
Run Code

The first line shows how we can normally use the JSON.parse() method. The second line shows the reviver's method along with the text. 

The text argument is the string that needs to be passed to convert it to JSON. The reviver argument is optional. The reviver argument shows how the value before the parsing is transformed. 

Return Value

It is essential to discuss what the method returns. The JSON.parse() method returns an Object, array, boolean, or NULL value depending on the given text input to the method. Essentially, we can think of the return type as simply Javascript Objects. 

Exceptions

A syntax error is thrown by the JSON.parse() method if the input string is not valid. This might have multiple reasons, and we will discuss them later in this blog.

Using the Optional Reviver Argument

As discussed above, the JSON.parse() method has an optional reviver argument. The reviver has a simple task to perform. The reviver transforms the data before it is parsed as JSON by the JSON.parse() method. Sometimes, the reviver has conditions such that it only transforms specific data and not all. In such cases, we must return all data un-transformed as it was. In simple words, the reviver function can be thought of as a filter. Let us try to understand the role of the reviver using an example. 

 

Consider the following code:

var sample = '{"1": "Apple", "2": "Ball", "3": "Dog", "4": "Cat"}';

var final = JSON.parse(sample, function (key, value) {
    if(key === 3)
        return "C";

    if(key === 4)
        return "D";

    return value; 
});

console.log(final);
You can also try this code with Online Javascript Compiler
Run Code

The output of this code would be:

{ 1: "Apple", 2: "Ball", 3: "Cat", 4: "Dog" }

 

Another critical thing to note for the reviver is that when the given JSON is nested, the reviver starts from the highest nested elements first, eventually going to the outermost elements and values. This can be seen from the following code. 

var sample = '{"one": 1, "two": 2, "three": {"four": 4, "five": {"six": 6}}}';
var final = JSON.parse(sample, function(key, value) {
    console.log(key); 
    return value; 
});
You can also try this code with Online Javascript Compiler
Run Code

Output:

one

two

four

six

five

three

""

 

The "" at the end is because the last key is always empty in the reviver parameter of the JSON.parse() method.

Try and compile by yourself with the help of online javascript compiler for better understanding.

Examples and Exceptions

We cannot use date objects in the JSON.parse() method. We cannot parse functions as well. The only workaround of both these things is to convert them to strings and then get them parsed, though this is not a very common practice. The parsing method also does not allow single quotes to be passed. All of these exceptions throw errors on the console. 

For example:

JSON.parse("{‘hello’: 10}") // This would throw an error on the console
You can also try this code with Online Javascript Compiler
Run Code

Some examples of JSON parsing could be:

JSON.parse('{}');  // This would return - {}
JSON.parse('true'); // This would return - true
JSON.parse('"hello world"');  // This would return - "hello world"
JSON.parse('null'); // This would return - null
You can also try this code with Online Javascript Compiler
Run Code

Frequently Asked Questions

1. Is JSON the same as Javascript?
No! JSON is simply a way to store data in text form, while Javascript is a programming language. 

2. Why do trailing commas throw an error while using JSON.parse()?
Trailing commas refer to commas that are added after the last entity in an object. To understand trailing commas, we can look at the following object:
let userStr = '{"name":"Gunjeev","email":"email@example.com",}';
If we look carefully, there is a comma at the end of the email field even though that is the last field of the object. This comma is referred to as a trailing comma. 

If the string passed has trailing commas, JSON.parse() throws an error as trailing commas are not valid in JSON.

3. Is JSON only used in Javascript applications?
JSON is used in almost all web and app projects, regardless of the project’s tech stack. Even a Django project would transfer JSON data.

Key Takeaways

This blog explained the concept of JSON, how and where it is used, and its syntax. Then we discussed the JSON.parse() method of Javascript. The JSON.parse() method is used to convert text inputs in string formats to Javascript JSON. The parse method is one of the two methods related to JSON. The second method is the Stringify Method, and you can learn that now from this blog.

 

Head over to our web development blogs to continue your learning journey!

Live masterclass