JavaScript: JSON (JavaScript Object Notation)

JavaScript: JSON (JavaScript Object Notation)

January 26, 2020
JSON: JAVASCRIPT OBJECT NOTATION

In this post, we’ll talk about JSON ( JavaScript Object Notation).

What is JSON?

JavaScript Object Notation (JSON) is an open-standard file format or data interchange format that uses human-readable text to transmit data objects consisting of attribute-value pairs and array data types (or any other serializable value). It is a very common data format, with a diverse range of applications, such as serving as a replacement for XML in AJAX systems. (Wikipedia)

2 things to know abut JSON

> Keys - a string wrapped in ""
> Values - can be a string, number, boolean expression, array, or object
{
	"name": "John",
	 age:	16,
	"ocean": {
			"chosen": true,
			"voyaged": false	
		 }
}
console.log(json.name); //John
console.log(json.age); //16

Example

var data = {
"employees":[
    {"firstName":"John", "lastName":"Doe"},
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
]
}

Explanation

{employees: Array(3)}

This example defines an employees object: an array of 3 employee records (objects)

data.employees[0].firstName
"John"

JSON: Data types

string
number
object (JSON object)
array
boolean
null

Difference between JSON text and the javascript object

Javascript Object is a variable type and JSON is a string(text).

JSON.parse()      - turn a string into JSON
JSON.stringify()  - turn JSON into a string

JSON.parse() – Convert text into a JavaScript object (turn a string into JSON)
JSON.stringify() – convert JavaScript object into a string (turn JSON into a string)