Part of Series: Javascript Handbook

How JSON works in Javascript

📣 Sponsor

JSON stands for Javascript Object Notation. It is a flexible way to store data, but ultimately it is a Javascript Object.

What does JSON look like?

JSON is a simple object structure. Sometimes, it is in separate files, with a .json ending, or sometimes it is in Javascript itself stored in a variable. APIs and NoSQL Databases often return data or store data as JSON.

Below is an example of a person described in JSON:

{ "firstName" : "John", "lastName" : "Smith", "age" : "99", "address" : { "streetAddress" : "123 Fake Street", "city" : "FakeTown", "zipCode" : "12345" }, "someIds" : [ 123, 234, 345 ] }

JSON is flexible, so the names you use are not set in stone. You can store any types of data as you normally would in Javascript (i.e. numbers, booleans, arrays, etc).

Working with JSON

JSON is often sent or received via APIs. As such, we have a few tools to manipulate JSON. The two biggest ones we have are JSON.parse and JSON.stringify. If we are sending JSON, we often stringify it, which will turn it into a string. Then, JSON-like strings can be turned back into a Javascript object using JSON.parse. Let's use our original JSON, and take a look at how these work:

let myJSON = { "firstName" : "John", "lastName" : "Smith", "age" : "99", "address" : { "streetAddress" : "123 Fake Street", "city" : "FakeTown", "zipCode" : "12345" }, "someIds" : [ 123, 234, 345 ] } let stringifyJSON = JSON.stringify(myJSON);

When we stringify our JSON, we end up with this, which is an escaped version of our original JSON in string form:

"{\"firstName\":\"John\",\"lastName\":\"Smith\",\"age\":\"99\",\"address\":{\"streetAddress\":\"123 Fake Street\",\"city\":\"FakeTown\",\"zipCode\":\"12345\"},\"someIds\":[123,234,345]}"

Using JSON.parse will turn that string back into a Javascript object:

let stringJSON = "{\"firstName\":\"John\",\"lastName\":\"Smith\",\"age\":\"99\",\"address\":{\"streetAddress\":\"123 Fake Street\",\"city\":\"FakeTown\",\"zipCode\":\"12345\"},\"someIds\":[123,234,345]}"; let parsedJSON = JSON.parse(stringJSON); // This is now a javascript object!
Last Updated 1625326924426

More Tips and Tricks for Javascript

Subscribe for Weekly Dev Tips

Subscribe to our weekly newsletter, to stay up to date with our latest web development and software engineering posts via email. You can opt out at any time.

Not a valid email