Javascript JSON parse()

Introduction

The Javascript JSON.parse() parses a JSON string to Json object.

JSON.parse(text[, processor])
  • text - The string to parse as JSON.
  • processor - Optional, processor to parsed json object.

It throws a SyntaxError exception if the string to parse is not valid JSON.

let a = JSON.parse('{}');              
console.log(a);// {}
a = JSON.parse('true');
console.log(a);// true
a = JSON.parse('"foo"');
console.log(a);// "foo"
a = JSON.parse('[1, 5, "false"]');
console.log(a);// [1, 5, "false"]
a = JSON.parse('null');
console.log(a);// null

Using the processor parameter. The following processor double the number value.

It leaves the other value unchanged.


let a = JSON.parse('{"p": 5}', (key, value) =>
   typeof value === 'number' ? value * 2 : value     
);
console.log(a);// { p: 10 }

The following processor logs the current property name.

It returns the unchanged property value.

let a = JSON.parse('{"1": 1, "2": 2, "3": {"4": 4, "5": {"6": 6}}}', (key, value) => {
  console.log(key); /*  w  ww .  j  av a2 s.c  o m*/
  return value;     
});
console.log(a);

JSON.parse() does not allow trailing commas

The following code will throw a SyntaxError.

let a= JSON.parse('[1, 2, 3, 4, ]');
console.log(a);
a = JSON.parse('{"foo" : 1, }');
console.log(a);

JSON.parse() does not allow single quotes

let a = JSON.parse("{'foo': 1}");
console.log(a);



PreviousNext

Related