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.





No comments:

Post a Comment