๐ŸŽ“ A1Learner
๐Ÿ”
0 of 38 lessons completed

JSON in Depth

JSON is a text format that holds data as name and value pairs and as lists. PHP can write values as JSON text and can read JSON text back into values.

An array becomes JSON text

json_encode reads the book array here. The printed line is the JSON text for that array.

<?php
$book = ["title" => "Dune", "pages" => 412];
echo json_encode($book) . "\n";

JSON text becomes an array again

The second argument true asks for an array. Square brackets then read the title and the page count from the array.

<?php
$json = '{"title":"Dune","pages":412}';
$book = json_decode($json, true);
echo $book["title"] . "\n";
echo $book["pages"] . "\n";

JSON text becomes an object

With no true argument, decode gives an object. A property is a named value in an object, and an arrow with the name reads it.

<?php
$json = '{"title":"Dune","pages":412}';
$book = json_decode($json);
echo $book->title . "\n";
echo $book->pages . "\n";

Pretty printing spreads the text

JSON_PRETTY_PRINT is an option passed to json_encode. The output spreads over lines, and the nested list indents under its name.

<?php
$book = ["title" => "Dune", "tags" => ["novel", "classic"]];
echo json_encode($book, JSON_PRETTY_PRINT) . "\n";

Example

<?php
$book = ["title" => "Dune", "pages" => 412];
$json = json_encode($book);
echo $json . "\n";
$back = json_decode($json, true);
echo $back["title"] . "\n";
echo $back["pages"] . "\n";

Key points

  • Use json_encode to turn a PHP value into JSON text.
  • Use json_decode to turn JSON text back into a PHP value.
  • json_decode with true as its second argument gives an array.
  • json_decode with no second argument gives an object.
  • JSON_PRETTY_PRINT makes json_encode spread its text over lines with indent.

In this example, json_encode turns the book array into JSON text and prints it. json_decode then reads that same text back into an array. The last two lines read the title and the page count from the returned array.

Note

JSON text is a string in PHP, so echo can print it like other text.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does json_decode give when true is its second argument?