How to Work with JSON Using JavaScript

JSON is a data format that you will encounter very often when it comes to web development. It is frequently used to transfer data between computers, as we will demonstrate later in this course.

JSON stands for JavaScript Object Notation, so naturally, it has a structure similar to a JavaScript object.

json
1{
2  "firstName": "John",
3  "lastName": "Doe",
4  "age": "25",
5  "child": {
6    "id": "123"
7  }
8}

In JavaScript, there are two methods under the JSON object. They allow you to convert JSON into a JavaScript object and vice versa.

The stringify() method converts objects into JSON:

javascript
1const obj = {
2  firstName: "John",
3  lastName: "Doe",
4  age: "25",
5  child: {
6    id: "123",
7  },
8};
9
10const json = JSON.stringify(obj);
11
12console.log(json);
text
1{"firstName":"John","lastName":"Doe","age":"25","child":{"id":"123"}}

And parse() converts JSON into an object:

javascript
1const json = `{"firstName":"John","lastName":"Doe","age":"25","child":{"id":"123"}}`;
2
3const obj = JSON.parse(json);
4
5console.log(obj.firstName);
6console.log(obj.lastName);
7console.log(obj.child.id);
text
1John
2Doe
3123

Wait, there is more!

You need an account to access the rest of this lesson. Our course is 50% off for limited time only! Don't miss the opportunity!

🎉 Create an Account 🎉