JavaScript object notation or JSON is a way to store and exchange data in string format for applications in JavaScript object notation.
When the data is exchanged,it is converted into <span style="color:#a30000" class="tadv-color">strings </span>
and when the application needs to manipulate the string values. It can <span style="color:#a32200" class="tadv-color">parse </span>
it back to JavaScript objects.
- stringify() – convert the JS objects into strings.
- parse() – converts the strings into JS objects.
Stringify Method
JSON is an independent format that can send text information or receive it. Therefore, any programming language can use it efficiently.
To convert a JavaScript object over the network is possible if we use JSON. It means we need to convert JavaScript object into text without loosing its format.
The stringify() function can convert any JavaScript object into string.
For example
//Create a JavaScript object
var person = {
firstName :'Peter',
lastName: 'Pan'
};
//Use JSON to convert the object into string
var jsonObj = JSON.stringify(person);
console.log(person);
//Output = {"firstName":"Peter","lastName":"Pan"}
The output of the program is following:
{"firstName":"Peter","lastName":"Pan"}
The output is a string and it cannot be manipulated.
For example
console.log(json.firstName);
//will return undefined
Parse Method
The parse() method does exactly opposite of stringify(). It converts the JSON string into a valid JavaScript object.
Let us continue our previous example and convert <span style="color:#a30500" class="tadv-color">jsonObj</span>
into a valid JavaScript object.
var jsObj = JSON.parse(jsonObj);
console.log(jsObj.firstName);
//output = "Peter"
Once benefit of using JSON is that it communicate faster than technologies like XML to exchange data.
JSON Example Program
In this example, we will be using PHP code that the server executes and send JSON information to the
//Server side PHP code that convert object into a JSON //format
<?php
$obj->name = "Peter";
$obj->age = 34;
$obj->salary = 1200;
echo json_encode($obj);
?>
//Use AJAX to get the data
<script>
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "ajax_info.txt", true);
xhttp.onload = function(e){
var jsonData = this.response;
}
//Parse the data into JavaScript objects
var jsObj = JSON.parse(jsonData);
//Print the name of the object
console.log(jsObj.name);
//output = 'Peter'