JavaScript JSON APIs/Methods Guide

1. Overview

The JSON object contains methods for parsing JavaScript Object Notation (JSON) and converting values to JSON. JSON is a syntax for serializing objects, arrays, numbers, strings, booleans, and null. It is based upon JavaScript syntax but is distinct from it: some JavaScript is not JSON.
In this guide, you will learn how JavaScript Objects can be converted into JSON, and JSON can be converted back into JavaScript Objects.

For the best learning experience, I highly recommended that you open a console (which, in Chrome and Firefox, can be done by pressing Ctrl+Shift+I), navigate to the "console" tab, copy-and-paste each JavaScript code example from this guide, and run it by pressing the Enter/Return key.

2. JSON Methods

JSON object provides two methods to convert Javascript object to JSON and vice versa:
  • JSON.parse() - Parses a JSON string and returns a JavaScript object
  • JSON.stringify() - Convert a JavaScript object to a JSON string
Below diagram shows the usage of the above APIs with examples:

2.1. JSON.parse()

The JSON.parse() method parses a string and returns a JavaScript object. 

Syntax

JSON.parse(text[, reviver])

Parameter Values

  • text - This is a required field. A string is written in JSON format
  • reviver function - This parameter an optional. A function used to transform the result.
An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.

JSON.parse() Method Examples

Here is a simple example using JSON.parse() method, which returns Javascript object:
var text = JSON.parse( '{ "firstName" : "Ramesh", "lastName" : "Fadatare",  "emailId" : "[email protected]",  "age" : "29"  }');
console.log(text);
Output:
{firstName: "Ramesh", lastName: "Fadatare", emailId: "[email protected]", age: "29"}
Note that above javascript object is printed in the console.
How to use the reviver function:
/*replace the value of "city" to upper case:*/
var text = '{ "name":"John", "age":"39", "city":"New York"}';
var obj = JSON.parse(text, function (key, value) {
  if (key == "city") {
    return value.toUpperCase();
  } else {
    return value;
  }
});
console.log(text);
Output:
{ "name":"John", "age":"39", "city":"New York"}
More examples:
JSON.parse('{}');              // {}
JSON.parse('true');            // true
JSON.parse('"foo"');           // "foo"
JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
JSON.parse('null');            // null

2.2 JSON.stringify() Method

The JSON.stringify() method converts a JavaScript object or value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.

Syntax

JSON.stringify(value[, replacer[, space]])

Parameters

  • value - This is a parameter is required. The value to convert to a JSON string.
  • replacer - This parameter is optional. Either a function or an array used to transform the result. The replacer is called for each item.
  • space - This parameter is optional. A String or Number object that's used to insert white space into the output JSON string for readability purposes.

JSON.stringify() Method Examples

Example 1: Let's create a Javascript object:
  var user = {
    firstName : 'Ramesh',
    lastName : 'Fadatare',
    emailId : '[email protected]',
    age : 29
  }
Convert above Javascript object into JSON string as:
JSON.stringify(user)
console.log(JSON.stringify(user));
Output:
{"firstName":"Ramesh","lastName":"Fadatare","emailId":"[email protected]","age":29}
Example 2: replacer argument example, as a function
function replacer(key, value) {
  // Filtering out properties
  if (typeof value === 'string') {
    return undefined;
  }
  return value;
}

var foo = {foundation: 'Mozilla', model: 'box', week: 45, transport: 'car', month: 7};
JSON.stringify(foo, replacer);
Output:
"{"week":45,"month":7}"
Example 3: replacer argument example, as an array
If replacer is an array, the array's values indicate the names of the properties in the object that should be included in the resulting JSON string.
var foo = {foundation: 'Mozilla', model: 'box', week: 45, transport: 'car', month: 7};
JSON.stringify(foo, ['week', 'month']);  
Output:
"{"week":45,"month":7}"
Example 4: The space argument example. The space argument may be used to control spacing in the final string.
JSON.stringify({ a: 2 }, null, ' ');
Output:
"{
 "a": 2
}"
Using a tab character mimics standard pretty-print appearance:
JSON.stringify({ uno: 1, dos: 2 }, null, '\t');
Output:
"{
 "uno": 1,
 "dos": 2
}

3. References

  1. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
  2. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

Comments