What is JSON in Javascript
JSON stands for JavaScript Object Notation. JSON objects are used to transfer data between server and client, JSON is easy to read and write than XML. JSON objects have several advantages over XML and we’ll discuss them in this tutorial, along with JSON concepts and their uses.
Let’s see an example of JSON: It contains data in the form of key-value pairs.
var person = { "name" : "Alex", "age" : "25", "address" : "Los Angeles" };
Features of JSON:
- Lightweight
- Independent of any language
- Easy to read and write
- Human-readable, text-based data exchange format
- Supports arrays, objects, strings, numbers, and values.
JSON data types
JSON defines 6 types of data :
1. String
{ "name": "Alex" }
4. Number
{ "age": 24 }
2. Object
{ "person": { "name": "Alex" } }
3. Array
{ "arr": [1, 2, 3, 4, 5, 6] }
Boolean
{ "open": true, "close": false }
5. Date
{ "birthdayDate": "1996-01-25 20:00:00 +0100" }
How to read the different types of JSON structure
1. JSON objects
var person = { "name" : "Alex", "age" : "25", "address" : "Los Angeles" };
We can access information like this:
document.writeln("Name is: " +person.name); document.writeln("Age is: " + person.age); document.writeln("Adress is: "+ person.address);
2. JSON objects in an array
In the example above, we’ve stored just one person’s information in a JSON object. Suppose we want to store the information of multiple people. in this case, we can have an array of objects.
var persons = [{ "name" : "Alex", "age" : "25", "address" : "Los Angeles" }, { "name" : "Emily", "age" : "22", "address" : "Chicago" }];
We can access information like this:
document.writeln("The name of the 1st person is: " +person[0].name); //Alex document.writeln("The name of the 2nd person is: " + person[1].name); //Emily
3. Nesting JSON objects:
Another way to do the same as we did in the example above.
var persons = { "p1" : { "name" : "Alex", "age" : "25", "address" : "Los Angeles" }, "p2" : { "name" : "Emily", "age" : "22", "address" : "Chicago" } }
We can access information like this:
document.writeln("The name of the 1st person is: " +persons.p1.name); //Alex document.writeln("The name of the 2nd person is: " + persons.p2.name); //Emily
Conclusion
In this tutorial, almost all aspects of JSON have been covered. We hope they give you the knowledge you need.