Skip to main content

Command Palette

Search for a command to run...

How To Parse JSON In JavaScript?

Updated
2 min read
How To Parse JSON In JavaScript?
S
Relentlessly curious and fiercely high‑agency, I'm a senior software engineer who thrives on taking products from zero to production‑ready in record time. Having worked across startups and fast-paced organizations, I've built a reputation as a cracked engineer who solves hard problems fast and owns the entire product stack end-to-end. My knack for rapid problem‑solving and end‑to‑end ownership turns complex ideas into polished, scalable products that ship fast and scale even faster. phewww... I love a cup of coffee ☕ while writing code. So let's connect and have a meet over something you wanna discuss. I'll be more than happy to have it. Book a call with me: https://cal.com/xshivank

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 🤔!

More from this blog

Shivank Kapur

57 posts

learning distributed systems 🦀 / dev-rel eng @routerprotocol / member @superteam / previously @thedogecapital @pushprotocol

How To Parse JSON In JavaScript?