Showing posts with label JSON. Show all posts
Showing posts with label JSON. Show all posts

Monday, April 16, 2018

JSON.parse


Whenever you are receiving data from a server, the data is may be a string. So to make the data as JS object we should use JSON.parse().


var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}');
console.log(obj); // Output will be in object format

var text = '{ "name":"John", "birth":"1986-12-10", "city":"New York"}';
var obj = JSON.parse(text);
obj.birth = new Date(obj.birth);

console.log(obj);

Explanation:
     Initially we have passed a string value into the parse method. So that now it will become an object.

In the third line, same concept we have used like line number 1 and 2. But after parse, we have modified birth date property. So now the Date will be added like correct date format.


JSON Reviver function:

The Reviver parameter is a function which will check each property, before returning the value.


var text = '{ "name":"John", "birthDate":"1986-12-10", "city":"New York"}';
var obj = JSON.parse(text, function (key, value) {
    if (key == "birthDate") {
        return new Date(value);
    } else {
        return value;
    }});


We are checking here for date, because we need to convert as a proper date format, not in string format. If you are not using parse reviver function, still you will use date as string only.
Hope you got it.





Custom - toJSON

Example I:


See the below example to understand custom toJson concepts. (Built in toJSON)

let Test = {
  number: 23
};

let TestingDate = {
  title: "DateTest",
  date: new Date(Date.UTC(2018, 0, 1)),
  Test
};

alert( JSON.stringify(TestingDate) );
/*
  {
    "title":"DateTest",
    "date":"2018-01-01T00:00:00.000Z",  // (1)
    "Test": {"number":23}               // (2)
  }
*/

Explanation:

        Here Date is showing perfectly after json convert. Because all dates have a built-in toJSON method which returns the correct string.

Example II: (custom toJSON)




let CustomCheck = {
  number: 23,
  toJSON() {
    return this.number;
  }
};

let CustomCheckTest = {
  title: "Something",
  CustomCheck
};

alert( JSON.stringify(CustomCheck) ); // 23

alert( JSON.stringify(CustomCheckTest) );
/*
  {
    "title":"Something",
    "CustomCheck": 23
  }
*/

Explanation:

This example is different, as we have mentioned toJSON separately. Means, we are not using in built toJSON.

In the initial customCheck object we have returned the number 23. So whenever you are using CustomCheck object , it will provide you 23.






What are the specific properties skipped by stringify

Some of JavaScript-specific object properties are skipped by JSON.stringify.

What are those ?

1. Function properties - means methods
2. Symbolic properties.
3. Properties that store undefined.


let user = {
  sayHi() { // ignored
    alert("Hello World");
  },
  [Symbol("id")]: 123, // ignored
  something: undefined // ignored
};

alert( JSON.stringify(user) ); // {} (empty object)



However, another good here is, nested objects are supported and converted automatically.


let testNestedObjects = {
  title: "NestedCheck",
  test1: {
    number: 123,
    participants: ["test25", "test26"]
  }
};

alert( JSON.stringify(testNestedObjects) );

Output:

{
  "title":"NestedCheck",
  "test1":{"number":123,"participants":["test25","test26"]},
}








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.