Array
University of Oregon

JSON

json-logo-2dor7vq The following is adapted from JavaScript: Novice to Ninja, by D. Jones.

See Also: JSON tutorial (w3schools)

JavaScript Object Notation (JSON)

JSON was invented by Douglas Crockford in 2001, and is a string representation of object literal notation.

There are a few differences: Property names must be double-quoted strings, and functions are not used to create methods.

It is a popular light-weight data-storage format that is used for data serialization to exchange information between web servers and clients.

JSON is employed by sites such as Twitter, Facebook, and Trello to share information.

JSON manages to hit the sweet spot between being both human- and machine-readable.

Example: the Caped Crusader

var batman =
'{"name": "Batman","real name": "Bruce Wayne","height":74,"weight": 210,
"hero": true,"villain": false,"allies": ["Robin", "Batgirl","Superman"]}';

JSON is becoming increasingly popular as a data storage format and many programming languages now have libraries dedicated to parsing and generating it. Since ECMAScript 5, there has been a global JSON object that can be used to do the same in JavaScript.

The parse method takes a JSON string and returns a JavaScript object:

    JSON.parse(batman);

The stringify method does the opposite, taking a JavaScript object and returning a string of JSON data, as can be seen in the example:

var wonderWoman = {name: "Wonder Woman", "real name": "Diana Prince"};
console.log(wonderWoman); // prints Object
var WWstr = JSON.stringify(wonderWoman);
console.log(WWstr);
//prints {"name":"Wonder Woman","real name":"Diana Prince"}

Note that any methods an object has will simply be ignored by stringify.

These methods are useful when passing data to and from a web server using Ajax requests or when using localStorage (e.g., files, Redis, MongoDB) to store data on a user s machine.

JSON vs XML

JSON is sometimes called, XML-lite.

Note that, to process an XML document, JavaScript must first convert the XML to JavaScript. JSON requires no such conversion.

Skip to toolbar