onlyforbopi
9/28/2018 - 7:06 AM

JS.JSON.Theory.Basics.Ex1

JS.JSON.Theory.Basics.Ex1

////////////////////////////
// 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);

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("p").hide();
    });
});
</script>
</head>
<body>

<h2>This is a heading</h2>

<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

<button>Click me to hide paragraphs</button>

</body>
</html>