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!
More Tips and Tricks for Javascript
- Javascript Reserved Keywords
- Updating Object Key Values with Javascript
- Javascript Proxy: Using Javascript Proxies like a Pro
- Making your own Email Subscription Service with Node.JS
- Making a Morphing 3D Sphere in Javascript with Three.js
- An Introduction to Javascript Objects
- How to Make Payments with the Javascript Payments API
- How does the Javascript logical AND (&&) operator work?
- How Events work in Javascript
- What are the three dots (...) or spread operator in Javascript?