JSON

JSON is a lightweight language independent data-interchange format. It is convenient for both people and machines. See more details and implementations on other languages on official page.

Any JSON text is a valid JavaScript expression, but not any JavaScript text is JSON.

  • JSON supports objects, arrays, numbers, strings, booleans, and null
  • property names must be double-quoted strings
  • leading zeros are prohibited for numbers
  • NaN and Infinity values for numbers not supported
  • undefined value not supported
  • comments not supported

For working with JSON the JSON type is used.

var jsonSrc = '{"width": 3, "height": 7, "descr": "wood stuff"}';  

var objDst = JSON.parse(strJson, (key, value) =>
  typeof value === 'number' // convert meters to millimeters
    ? value * 1000 
    : value     
);

console.log(objDst);

var objSrc = {width: 3, height: 7, descr: "wood stuff"};

var jsonDst = JSON.stringify(objSrc, (key, value)=>{
     if (typeof value === 'string') {
       return undefined;
     } 
     return value;
   }, 4);
    
console.log(jsonDst)
/* result:
{
    "width": 3,
    "height": 7
}*/

static methods

method description
parse(text[, reviver]) Parses the string text as JSON. A SyntaxError exception will be thrown if any error.
The optional reviver parameter is a function with two parameters: key and value. Returns transformed value.
stringify(value
[, replacer
[, space]])
Converts a JavaScript object or value to a JSON string
The optional replacer parameter is function with two parameters: key and value. Returns value that will be saved in string.
The optional space parameter may be used to control spacing in the final string. Possible values are:
  • number in a range [0; 10]
  • string for indented, usually consists from spaces or tabulators