JSON.parse()

JSON.parse() method parses a JSON string, constructing the JavaScript values or an object which is described by the string. A reviver optional function can be provided to perform some transformation on the given object before it is returned.

Syntax :

JSON.parse(text[, reviver])

Parameters :

text :

The string to parse a JSON .

reviver : (optional)

This specifies how the value will be produced by parsing it, before the result is returned.

return value :

It returns the object which is based on the given JSON text.

Exceptions :

If the string to parse is not valid then it throws a syntax error.


Examples :

JSON.parse('{}') // {}
JSON.parse('true') // true
JSON.parse('"hello"') // "hello"
JSON.parse('[1,2,3]') // [1,2,3]
JSON.parse('null') //null

parameter : reviver

reviver specifies the value computed by parsing is transformed before it is being returned, the values and its properties will run individually through the reviver. Then it is called with the name and value i.e, name as String, value as argument. If reviver is undefined or no value then the property is deleted from the object.

Example :

1. JSON.parse( '{"no":10}', (key,value)  =>

typeof value === 'number'
          ? value * 10 // if typeof value is number then it returns 100
           : value // else it returns 10, the value will not be changed
);
output : 100

2. JSON.parse('{
"first": 1,
"second": 2,
"third": {
"fourth": 4,
"fifth": {
"sixth": 6
}
}
}
', (key, value) => {
console.log(key); 
return value; 
});

output : 

first
second
fourth
sixth
fifth
third

JSON.parse() doesn't allow trailing commas, it throws a syntax error. i.e,

JSON.parse('[1,2,3,]')

JSON.parse('{"name":"blog",}')


No comments:

Post a Comment

Overview of AngularJS

AngularJS is an open source web application framework. It is now maintained by Google . The most of the code can be eliminated by using th...