Chapter 5. JSON

JSON stands for JavaScript Object Notation, but don’t be fooled by the name. Although it sounds as if it’s a JavaScript-specific format, it is supported by most programming languages today. It’s a very simple, lightweight format, which can represent nested, structured data.

For example, consider a data set that looked like this:

  • message

    • en: “hello friend”

    • es: “hola amigo”

In JSON, that data would look like this:

{"message":{"en":"hello friend","es":"hola amigo"}}

If a piece of data is represented by a scalar value, then it is presented plainly. If it is structured (as shown in the previous example), such as an associative array or an object with properties in PHP, a curly brace is used to indicate a new level of depth in the data structure. The keys and values are separated by colons, and each record at a given level is separated with a comma.

It is also possible to show a list of items quite elegantly using JSON. Take this imaginary shopping list:

  • eggs

  • bread

  • milk

  • bananas

  • bacon

  • cheese

A JSON representation of this would simply be:


As you can see here, many of the keys in the previous example are optional, and multiple values are enclosed with the simple square brackets. If this list was in fact the value of a property, then both kinds of brackets would be seen:


This example shows that our data contained a key/value pair, with the ...

Get PHP Web Services, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.