Monday, April 16, 2018

JSON methods

Generally we will use JSON for sending data over the network like Rest web service call etc.,

We can see some important methods here.

1. JSON.stringify -  to convert objects into JSON.

2. JSON.parse      -  to convert JSON back into an object.



let student = {
  name: 'Rajini',
  age: 30,
  isAdmin: false,
  courses: ['css', 'js']
};

let json = JSON.stringify(student);

alert(typeof json); // Its String now.

alert(json);
/* JSON-encoded object:
{
  "name": "Rajini",
  "age": 30,
  "isAdmin": false,
  "courses": ["css", "js"]
}
*/


Things to Remember Here:

1. Strings use double quotes. No single quotes or backticks in JSON. So 'Rajini' becomes "Rajini".

2. Object property names are double-quoted also. That’s obligatory. So age:30 becomes "age":30.

3. JSON.stringify can be applied to primitives also.


JSON supported types are:

Objects { ... }
Arrays [ ... ]
Primitives:
strings,
numbers,
boolean values true/false,
null.







No comments:

Post a Comment