JSON is also called java script object notation. Basically used in the computer science / software development for exchange and storing the data.

JSON is a just a text format written with the java script object notation. It is lightweight data-interchange format, self-describing and language independent.

As JSON is used to communicate data between the browser and the server in the text form. Also it is widely can be used for server to server communication.

Before sending the object to the server a java script object is converted to JSON (text). Also convert any JSON received from the server into JavaScript objects. These conversion usually use JavaScript method JSON.stringify(object) & JSON.parse(json)

Convert Object to JSON example

let myObject = {name: "ryan", age: 21, city: "Australia"};
let myJSON = JSON.stringify(myObject);

Convert JSON to JavaScript Object example

let myJSON = '{name: "ryan", age: 21, city: "Australia"};';
let myObject = JSON.parse(myJSON);

JSON Syntax: It follow some rule for syntax, as it is derived from JavaScript object notation syntax.

  • Data must be in name/value pairs. Ex. age:13
  • Data must be separated by commas. Ex. { age:13, name: ‘ryan’ }
  • Curly braces hold objects & Square brackets hold arrays Ex. { age:13, name: ‘ryan’, educations: [] }

The JSON format is almost identical to JavaScript objects. In JSON, keys must be strings, written with double quotes.

//json
{ "name":"ryan" }

//java script
{ name:"John" }

JSON vs Javascript Values

JSONJava Script
a string
a number
an object (JSON object)
an array
a boolean
null
a string
a number
an object (JSON object)
an array
a boolean
null

+

a function
a date
undefined

Access JavaScript value(s)

let data = { age:13, name: 'ryan', educations: [{}, {}, ....] }

// read attribute
let age  = data.age;
or
let age = data[age]

// modify age attribute
data.age = 20;
or 
data[age] = 20;

File Type:

  • The file type for JSON files is “.json
  • The MIME type for JSON text is “application/json

Arrays in JSON:

let data = { age:13, name: 'ryan', educations: ["BBA", "MBA"]}

Access arrays:

// first element
e1 = data.educations[0];  //BBA

// in loop 
for (e in data.educations) {
  e1 += data.educations[e];
}

Similar Posts