Table of Contents
Introduction to JSON
JSON stands for JavaScript Object Notation and is a data format meant to store and transfer data. You've seen a format very similar to it any time you've logged JavaScript objects in your console.
You can think of JSON as a string-representation of the data inside a JavaScript object. As such, JSON supports the following values:
- string
- number
- object
- array
- boolean
- null
Here's an example of some JSON containing data about a random fictional person:
JSON{
"name": "Josh",
"weight": 175,
"age": 40,
"eyecolor": "brown",
"cars": [ "Chevy", "Toyota", "Honda" ],
"favoriteBook": {
"title": "When the Fire Nation Attacked",
"author": "Nickelodeon",
"released": "02-21-2005"
}
}
Javascript and JSON work really together thanks to the methods stringify
and parse
, provided by the JSON
object.
These two methods convert a JavaScript object to JSON and back, so no matter which one you have, you can easily generate the other.
Stringify
You can use the stringify
method to convert a JavaScript object to JSON.
JAVASCRIPTconst dog = {
"name": "Sophie",
"age": 3,
"weight": 20
}
const dogJSON = JSON.stringify(dog);
console.log(dogJSON);
HTML{"name":"Sophie","age":3,"weight":20}
Using stringify on a JavaScript object.
Stringify took the dog
JavaScript object and converted it into a string. That string is now valid JSON and can be saved to a file or transferred over the network.
Parse
To get a JavaScript object from JSON, you must parse it, essentially the reverse of using stringify
. Using the results we got above, let's parse that JSON and turn it into a JavaScript object:
JAVASCRIPTconst json = '{"name":"Sophie","age":3,"weight":20}';
const dog = JSON.parse(json);
console.log(dog);
Parsing JSON into a JavaScript object.
Now that dog
is a normal JavaScript object, you can now use it as if it were created without JSON at all.
Resources
- Getting Started with Solid
- Getting Started with Express
- Create an RSS Reader in Node
- How to build a Discord bot using TypeScript
- How to deploy a Deno app using Docker
- How to deploy a Node app using Docker
- How to Scrape the Web using Node.js and Puppeteer
- Getting Started with Handlebars.js
- Creating a Twitter bot with Node.js
- Building a Real-Time Note-Taking App with Vue and Firebase
- Getting Started with Vuex: Managing State in Vue
- Using Axios to Pull Data from a REST API