Learn to process JSON in JavaScript

0
9714
process JSON

What is JSON

JSON is a subset of JavaScript which is a really good way to exchange and store data between clients and servers in the form of JSON objects. JSON pretty looks like JavaScript objects, that’s why JSON actually called JavaScript Object Notation. But it has some differences. It actually works like XML but more simpler and light in weight than XML. It can be complex sometimes but not really too hard to understand because it’s completely human readable.

JSON uses JavaScript’s syntax to store data as an object but we have to add double quotes to the key and the value.

Here I’m just giving a simple example to store JSON data.

Now in the above example, we just created an object using JSON techniques. We firstly created a variable named ‘person’ we inserted some data inside that variable.
And

is a JavaScript method which can write or print any string or integer to the webpage.

To call any object, just type its name and then press ‘.’ And type the ‘key’ “people.name”. You’ll get the key’s value from the specific object.

We have to create an array in case of more than one person.

JSON with array method

For creating an array, we use ‘[]’ brackets.

Creating an array is a little bit tricky to understand but not too hard. You just have to focus on the place of ‘[]’ & ‘{}’ brackets.

Firstly we create an object named ‘people’, than inside that object just put an array named ‘person’ and use ‘[]’ brackets. Inside ‘person’ array, just add ‘{}’ braces and start adding data.

After completing single person data, add another comma ‘,’ and insert another pair of ‘{}’ and insert another data. Just do it again and again as much as you need.

Nested JSON object

We also can nest objects into an object or an array. As you can see below:

Nesting of some objects inside an object looks a bit tricky as well but easy to understand. Just insert the key, and instead of inserting its value, insert ‘{}’ braces and start inserting keys and value again and again. At the above example, “skills” is a nested object inside person array which is held inside people object.

I just collected some information of the person named “Chris” in the above example. His name, his height, age, eye color and his skills. But it has many skills so Instead of inserting skills value, I just converted “skills” into an object. And inserted some more keys and values inside the nested object called “skills”.

In the above example, I’m just calling many properties of people. And many of the nested values.
For calling a nested object just follow the mentioned syntax “obj.arr.[].nestedobj.key”
Example:

I hope you guys understood how to work with JSON.

LEAVE A REPLY

Please enter your comment!
Please enter your name here