DEV Community

Cover image for Check Every property Before JSON Parse Data into a JS Object.
Asela
Asela

Posted on

Check Every property Before JSON Parse Data into a JS Object.

Today, I'll explain how to check each property when you parser JSON into a JS Object.

The answer is simple; We add a second parameter to our code which call reviver, to accomplish this.

const text = '{"name":"John", "birth":"1986-12-14", "city":"New York"}';
const obj = JSON.parse(text, function (key, value) {
  if (key == "birth") {
    return new Date(value);
 } else {
    return value;
  }
});
Enter fullscreen mode Exit fullscreen mode

According to this example, we get two parameters: ' key' and 'value. We check if the key is equal to "birth," and if it does, the value will change as data format, and If not, nothing will happen.

So cool and short, Isn't it? If this is helpful, don't ignore following me

Discussion (0)