JavaScript: JSON Methods

By Xah Lee. Date: . Last updated: .

JSON is the value of a property key "JSON" of the global object.

console.log( window.hasOwnProperty ( "JSON" ) ) // true

JSON is object.

// type of JSON
console.log ( typeof JSON === "object" ); // true
console.log ( Object.prototype.toString.call( JSON ) === "[object JSON]" ) // true

The parent of JSON is Object.prototype. 〔➤see JavaScript: Prototype and Inheritance

// parent of JSON
console.log ( Object.getPrototypeOf ( JSON ) === Object.prototype ); // true

Purpose of JSON

JSON is a static object.

JSON is not a function. You cannot call it, nor call it with new.

The purpose of JSON is as a namespace to hold functions, for working with the JSON data interchange format.

What's JSON?

What is JSON?

JSON is a data interchange format.

You can learn about it at http://www.json.org/

The easiest way to understand JSON, is that it is a JavaScript Object data in string form.

Another way to think of JSON is that it's just a nested key/value or array, where values may again be array or other key/value pairs.

For example, here's a JSON:

{
  "firstName": "John",
  "lastName": "Smith",
  "isAlive": true,
  "age": 25,
  "address": {
    "streetAddress": "21 2nd Street",
    "city": "New York",
    "state": "NY",
    "postalCode": "10021-3100"
  },
  "phoneNumbers": [
    {
      "type": "home",
      "number": "212 555-1234"
    },
    {
      "type": "office",
      "number": "646 555-4567"
    }
  ],
  "children": [],
  "spouse": null
}

Properties

The JSON object has just 2 properties, both are functions.

Note: You call JSON methods directly, you don't create JSON object.


JSON.stringify

JSON.stringify(js_object) → convert a JavaScript object to JSON string format. ES5 §15#sec-15.12.3

console.log(
JSON.stringify({a:3 , b:[4,2]})
// returns a string
);

JSON.stringify takes optional 2nd and 3rd args. For detail, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

ECMAScript 2015 §Structured Data#sec-json.stringify

JSON.parse

JSON.parse(json_string) → convert JSON string to a JavaScript value. ES5 §15#sec-15.12.2

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

// prints { a: 3, b: [ 4, 2 ] }

JSON.parse takes optional 2nd arg. For detail, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

ECMAScript 2015 §Structured Data#sec-json.parse

Reference

ECMAScript 2015 §Structured Data#sec-json-object

ES5 §15#sec-15.12

Method Reference

  1. JavaScript: Array Methods
  2. JavaScript: String Methods
  3. JavaScript: String Methods for Regex
  4. JavaScript: RegExp Object
  5. JavaScript: Regex Syntax
  6. JavaScript Date Object
  7. JavaScript: JSON Methods
  8. JavaScript: Math Methods
Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.