////////////////////////////
// Javascript and JSON
//
// JSON is the standard of exchanging information
// with remote servers / http servers.
//
// Mechanism for transforming complex objects into
// human readable string representations.
//
// It was made to replace XML as the format for exchanging
// data between servers (cleint / remote HTTP server.)
//
// V.Popular - AJAX communications with http servers
//
// Used for storing objects in LocalStorage. If we want to save
// a javascript object, we will have to turn it into JSON, then save
// it. When we read from the datastore, we retrieve the JSON,
// and turn it back into an object. Note: LocalStorage is
// the space reserved by the browser to be used as a small db for
// the application.
//
// Schematic of Function:
//
// Storing Object in LocalStorage:
// Object -> JSONstring -> Local Storage
//
// Retrieving Object from LocalStorage:
// LocalStorage -> JSONstring -> Object
//
// 1. object to JSON -> JSON.stringify(obj)
// 2. JSON to object -> JSON.parse(jsonString)
// ex 1 - simple int -> will return string int
var x = 3;
var JsonString1 = JSON.stringify(x);
console.log(JsonString1);
var JsonStringtoObj = JSON.parse(JsonString1);
console.log(JsonStringtoObj);
// ex 2 - with simple array
var x = [ 1, "2", "The", 3];
var JsonString1 = JSON.stringify(x);
console.log(JsonString1);
var JsonStringtoObj = JSON.parse(JsonString1);
console.log(JsonStringtoObj);
// ex 2 - with simple object, dict
var x = {
x:12,
y:30
}
var JsonString1 = JSON.stringify(x);
console.log(JsonString1);
var JsonStringtoObj = JSON.parse(JsonString1);
console.log(JsonStringtoObj);
// ex 2 - with simple object, dict
var x = {
x : 12,
y : 30,
z : [ 1, 2, 3 ]
}
var JsonString1 = JSON.stringify(x);
console.log(JsonString1);
var JsonStringtoObj = JSON.parse(JsonString1);
console.log(JsonStringtoObj);
// ex 2 - with simple object, dict
var x = {name:'Metallica',
albums:[
{name:"Master of Puppets", year:1986},
{name:"Black Album", year:1991}
]
};
var JsonString1 = JSON.stringify(x);
console.log(JsonString1);
var JsonStringtoObj = JSON.parse(JsonString1);
console.log(JsonStringtoObj);
// Accessing elements is not possible in a jsonstring, only in object.
console.log(x.name);
console.log(x.albums);
console.log(x.albums[0]);
console.log(JsonString1.name);
console.log((JSON.parse(JsonString1)).name)
JS.JSON.AccessingElements.Ex1
-----------------------------
A [Pen](https://codepen.io/Onlyforbopi/pen/gBOoPO) by [Pan Doul](https://codepen.io/Onlyforbopi) on [CodePen](https://codepen.io).
[License](https://codepen.io/Onlyforbopi/pen/gBOoPO/license).