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 easily readable and writeable by a wide range of scripting languages today. It’s a very simple, lightweight format, which can represent nested, structured data.
For example, if there were 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:
[
"eggs"
,
"bread"
,
"milk"
,
"bananas"
,
"bacon"
,
"cheese"
]
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:
{
"list"
:[
"eggs"
,
"bread"
,
"milk"
,
"bananas"
,
"bacon"
,
"cheese"
]}
This example shows that our data contained a key/value pair, ...
Get PHP Web Services 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.