Chapter 19. JSON—Native JavaScript Object Notation

IN THIS CHAPTER

  • How JSON works

  • Sending and receiving JSON data

  • JSON object methods

  • Security concerns

JSON (JavaScript Object Notation) is a lightweight way to represent data structures that many programming languages can easily read and write. This makes it (similarly to XML) a useful data interchange format among applications written in a variety of languages, for example, between server-side PHP and client-side JavaScript. With the ECMAScript Fifth Edition standard, JSON is now formally part of the language and will be increasingly supported by more browsers over the coming years. In the meantime, there is freely available code to assist older browsers.

JSON was developed by Douglas Crockford and presented to the Internet community in 2006. It was formally made part of the ECMAScript standard, on which JavaScript is based, as of the Fifth Edition finalized in April 2010.

How JSON Works

JSON combines two aspects of JavaScript syntax for representing arrays and objects to present data structures—simple array notation using brackets [ ]:

[ "item1", "item2", "item3" ]

and the notation for objects and associative arrays using curly braces { }:

{ "key": "value" }

We have access to the embedded values by numerical index in the first case (remember that the first item has an index of zero):

var aItems = [ "item1", "item2", "item3" ];
// e.g., aItems[0] == "item1"

and by key name in the second:

var oExample = { "charlie": "horse" }; // oExample["charlie"] ...

Get JavaScript® Bible, Seventh Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.