Chapter 13. JSON

Similar to XML, JavaScript Object Notation (JSON) was designed as a standardized data-interchange format. However, unlike XML, JSON is extremely lightweight and human-readable. While it takes many syntax cues from JavaScript, JSON is designed to be language-independent.

JSON is built on two structures: collections of name/value pairs called objects (equivalent to PHP’s associative arrays) and ordered lists of values called arrays (equivalent to PHP’s indexed arrays). Each value can be one of a number of types: an object, an array, a string, a number, the Boolean values TRUE or FALSE, or NULL (indicating a lack of a value).

Using JSON

The json extension, included by default in PHP installations, natively supports converting data to JSON format from PHP variables and vice versa.

To get a JSON representation of a PHP variable, use json_encode():

$data = array(1, 2, "three");
$jsonData = json_encode($data);
echo $jsonData;
[1, 2, "three"]

Similarly, if you have a string containing JSON data, you can turn it into a PHP variable using json_decode():

$jsonData = "[1, 2, [3, 4], "five"]";
$data = json_decode($jsonData);
print_r($data);
Array( [0] => 1 [1] => 2 [2] => Array( [0] => 3 [1] => 4 ) [3] => five)

If the string is invalid JSON, or if the string is not encoded in UTF-8 format, a single NULL value is returned instead.

The value types in JSON are converted to PHP equivalents as follows:

object
An associative array containing the object’s key-value pairs. Each value is converted into its PHP equivalent as well.
array
An indexed array containing the contained values, each converted into its PHP equivalent as well.
string
Converts directly into a PHP string.
number
Returns a number. If the value is too large to be represented by PHP’s number value, it returns NULL, unless json_decode() is called with the JSON_BIGINT_AS_STRING (in which case, a string is returned).
boolean
The Boolean true value is converted to TRUE; the Boolean false value is converted to FALSE.
null
The null value, and any value that cannot be decoded, is converted to NULL.

Serializing PHP Objects

Despite the similar names, there is no direct translation between PHP objects and JSON objects—what JSON calls an “object” is really an associative array. To convert JSON data into an instance of a PHP object class, you must write code to do so based on the format returned by the API.

However, the JsonSerializable interface allows you to convert objects into JSON data however you like. If an object class does not implement the interface, json_encode() simply creates a JSON object containing keys and values corresponding to the object’s data members.

Otherwise, json_encode() calls the jsonSerialize() method on the class and uses that to serialize the object’s data.

Example 13-1 adds the JsonSerializable interface to the Book and Author classes.

Example 13-1. Book and Author JSON serialization
class Book implements JsonSerializable {
 public $id;
 public $name;
 public $edition;

 public function __construct($id) {
 $this->id = $id;
 }

 public function jsonSerialize() {
 $data = array(
 'id' => $this->id,
 'name' => $this->name,
 'edition' => $this->edition,
 );

 return $data;
 }
}

class Author implements JsonSerializable {
 public $id;
 public $name;
 public $books = array();

 public function __construct($id) {
 $this->id = $id;
 }

 public function jsonSerialize() {
 $data = array(
 'id' => $this->id,
 'name' => $this->name,
 'books' => $this->books,
 );

 return $data;
 }
}

Creating a PHP object from JSON data requires you to write code to perform the translation.

Example 13-2 shows a class implementing Factory-style transformation of JSON data into Book and Author instances into PHP objects.

Example 13-2. Book and Author JSON serialization
class ResourceFactory {
 static public function authorFromJSON($jsonData) {
 $author = new Author($jsonData['id']);
 $author->name = $jsonData['name'];

 foreach ($jsonData['books'] as $bookIdentifier) {
 $this->books[] = new Book($bookIdentifier);
 }

 return $author;
 }

 static public function bookFromJSON($jsonData) {
 $book = new Book($jsonData['id']);
 $book->name = $jsonData['name'];
 $book->edition = (int) $jsonData['edition'];

 return $book;
 }
}

Options

The JSON parser functions have several options you can set to control the conversion process.

For json_decode(), the most common options include:

JSON_BIGINT_AS_STRING
When decoding a number that is too large to be represented as a PHP number type, returns that value as a string instead.
JSON_OBJECT_AS_ARRAY
Decodes JSON objects as PHP arrays.

For json_encode(), the most common options include:

JSON_FORCE_OBJECT
Encodes indexed arrays from the PHP values as JSON objects instead of JSON arrays.
JSON_NUMERIC_CHECK
Encodes strings that represent number values as JSON numbers, rather than as JSON strings. In practice, you’re better off converting manually, so you’re aware of what the types are.
JSON_PRETTY_PRINT
Uses whitespace to format the returned data to something more human-readable. Not strictly necessary, but makes debugging simpler.

Finally, the following options can be used for both json_encode() and json_decode():

JSON_INVALID_UTF8_IGNORE
Ignores invalid UTF-8 characters. If JSON_INVALID_UTF8_SUBSTITUTE is also set, replaces them; otherwise, drops them in the resulting string.
JSON_INVALID_UTF8_SUBSTITUTE
Replaces invalid UTF-8 characters with xfffd (the Unicode character 'REPLACEMENT CHARACTER').
JSON_THROW_ON_ERROR
Throws an error instead of populating the global last error state when an error occurs.

What’s Next

When you’re writing PHP, one of the most important things to consider is the security of your code, from how well the code can absorb and deflect attacks to how you keep your own and your users’ data safe. The next chapter provides guidance and best practices to help you avert security-related disasters.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.63.87