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 TypeScript
- How to Install Node on Windows, macOS and Linux
- Create an RSS Reader in Node
- How to Set Up Cron Jobs in Linux
- How to deploy a PHP app using Docker
- How to deploy a MySQL Server using Docker
- Getting Started with Sass
- Getting Started with Handlebars.js
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Creating a Twitter bot with Node.js
- Building a Real-Time Note-Taking App with Vue and Firebase
- Using Axios to Pull Data from a REST API