My Journey to Learning Javascript: Notes- Javascript Object Notation Specification ( JSON)

JSON, an data-interchange format, is based on a subset of the Javascript programming language that easily parses into JavaScript objects and serializes objects into JSON. JSON lets you represent three types of data: simple values, objects, and arrays.
Simple Values
Simple values like strings, numbers, booleans, and null can be represented by JSON. While javascript and JSON look similar they have their differences. For example strings must use double quotes.
“Javascript”
*this is valid JSON
‘Javascript’
*this is not valid
Numbers, booleans and null look similar to that of javascript. These are all valid JSON
10
true
false
null
Objects in JSON
Objects in JSON look somewhat similar to javascript object literal notation.
var person = { firstName: “Juan”, lastName: “Doe”, age: 24
};
Here is the same code in JSON:
{ “firstName”: “Juan”, “lastName”: “Doe”, “age”: 24
}
JSON is not a language so it does not use variables, functions, or methods. In JSON property names are strings so since all strings in JSON are put in double quotes, they are placed in double quotes as well. Aso since JSON is all data format, semicolons are needed
Arrays
Arrays in JSON are also similar to javascript notation.
var myInfo= [“Juan”, 24, false, null];
The same array in JSON:
[“John”, 24, false, null]
Since in JSON this would be just data instead of a statement, no variable or semicolon is needed.
A more complex example:
[ { “firstName”: “Juan”, “lastName”: “Doe”, “age”: 24, “address”: { “numberAndStreet”: “123 Someplace”, “city”: “Houston”, “state”: “Texas” } }, { “firstName”: “Jane”, “lastName”: “Doe”, “age”: 24, “address”: { “numberAndStreet”: “246 Someplace”, “city”: “Houston”, “state”: “Texas” } }
]
Serializing Javascript into JSON
To serialized javascript into JSON you simply use the JSON object’s stringify() method. Stringify() accepts a value, object or array and and serializes it into JSON. Example:
var myInfo={ “firstName”: “Juan”, “lastName”: “Doe”, “age”: 24, “address”: { “numberAndStreet”: “123 Someplace”, “city”: “Houston”, “state”: “Texas” }
var json= JSON.stringify(myInfo)
The myInfo object is serialized into JSON-formatted data, removing unnecessary white-space. It looks like this:
{“firstname”: “Juan”, “lastName”: “Doe”,“age”: 24,“address”: {“numberAndStreet”: “123 Someplace”,“city”: “Houston”, “state”: “Texas”}}
Parsing JSON
parsing JSON is also simple. It uses the parse() method. Example using the same code:
var juanDoe = JSON.parse(json)
This code parses the code placed into the variable json from the previous example and stores it into the new variable juanDoe.
JSON is useful when an API only lets you store text but you need to store an object.