cover-img

Contributors

Tapas Adhikary

21 April, 2022

How to parse JSON in JavaScript

It is very likely for you to deal with JSON as a web developer. One everyday use case is parsing JSON in JavaScript and handling errors. Let's learn.

Contributors

Tapas Adhikary

19

19

2

What is JSON?

JSON, also known as JavaScript Object Notation, is a text-based data exchange format. It is a collection of key-value pairs with a few rules to keep in mind,

  • The key must be a string type and enclosed in double-quotes.
  • The value can be of any type, String, Boolean, Number, Object, Array, and null.
  • A colon separates the key-value pair (:).
  • Multiple key-value pairs are separated by a comma(,).
  • All the key-value pairs must be enclosed within the curly braces({...})
  • You can not use comments(like /.../ or //...) in JSON.

Alright, with all that, let us see an example of JSON,


How to Parse JSON in JavaScript?

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


The output is a JavaScript Object,

JS Employee OBJ

How to Handle a Parsing Error?

When you parse a JSON text, you are likely to encounter a parsing error like this,

Parsing Error

It is mainly because the JSON is not a valid one. You must have missed one of the rules we have discussed above. Also, you are likely to forget to enclose the JSON text in a single quote('') or backtick(``) while assigned to a variable in JavaScript.

When you encounter such errors, please validate your JSON with a JSON Linter.

That's all for now. I hope you find this article helpful.

Let's connect,

json
javascript
#javascript
js
tips

19

19

2

19

19

2

Tapas Adhikary
Writer . YouTuber . Creator . Mentor | Building reactplay.io

More Shows