How To Parse JSON In JavaScript?

How To Parse JSON In JavaScript?

ยท

2 min read

What Is JSON?

JSON, JavaScript Object Notation, is a text-based way of representing JavaScript objects like- literals, arrays, and scalar data. JSON is quite easy to understand and write, while also easy for software to parse and generate.

JSON is a collection of key-value pairs with a few rules to keep in mind:

  • The key must be a string type and should be enclosed within double quotes.

  • The value can be of any type: String, Number, Array, etc.

  • A (:) is used to separate the key-value pair.

  • Multiple key-value pairs are separated by a comma(,).

  • All the key-value pairs must be enclosed within curly braces({...}).

Let's understand this with the help of an example:

{
    "name": "Rohit Raj",
    "profession": "Dancer",
    "age": 27,
    "city" : "Delhi"
}

How To Parse JSON In JavaScript?

We need to use JSON.parse() method in JavaScript to parse a valid JSON string in the required JavaScript Object.

const employee = `{
    "name": "Rohit Raj",
    "profession": "Dancer",
    "age": 27,
    "city" : "Delhi"
}`;

const employeeObj = JSON.parse(employee);
console.log(employeeObj);

The output will be a JavaScript Object.

How To Handle a Parsing Error?

While parsing a JSON text, one might encounter an error that would get displayed in your console.

There could be numerous reasons for that error some of which are mentioned below:

  • You must have missed any of the rules which we discussed above.

  • You might have forgotten to enclose the JSON text with a single quote("") or backtick(``).

If you encounter any such errors then validate your JSON with a JSON Linter.

I hope that you must have found this article quite helpful. If yes, then do give a read to some of my other articles!

Who knows you might become a great programmer ๐Ÿค”!

ย