PHP JSON Parsing

What is JSON

JSON stands for JavaScript Object Notation. JSON is a standard lightweight data-interchange format that is fast and easy to parse and generate.

JSON, like XML, is a text-based format that is simple to write and understand for both humans and computers. However, JSON data structures require less bandwidth compared to their XML counterparts. JSON is based on two fundamental structures:

  • Object: This is defined as a collection of key/value pairs (e.g., key:value). Each object starts with a left curly bracket { and ends with a right curly bracket }. Multiple key/value pairs are separated by commas ,.
  • Array: This is defined as an ordered list of values. An array begins with a left bracket [ and ends with a right bracket ]. Values are separated by commas ,.

In JSON, keys are always strings, while values can be a string, number, true or false, null, or even an object or an array. Strings must be enclosed in double quotes " and can include escape characters like \n, \t, and \. An example of a JSON object is:

{
"book": {
"name": "Harry Potter and the Goblet of Fire",
"author": "J. K. Rowling",
"year": 2000,
"genre": "Fantasy Fiction",
"bestseller": true
}
}

For instance, a JSON array would appear similar to the following:

{
"fruits": [
"Apple",
"Banana",
"Strawberry",
"Mango"
]
}

 

Tip: A data-interchange format is a text-based format used to exchange data between different platforms and operating systems. JSON, being lightweight and widely adopted, is the preferred choice for web applications.


Parsing JSON with PHP

JSON data structures closely resemble PHP arrays. PHP provides built-in functions for encoding and decoding JSON data: json_encode() and json_decode(). These functions exclusively handle UTF-8 encoded string data.

Encoding JSON Data in PHP

In PHP, you use the json_encode() function to convert a value into JSON format. The value can be any PHP data type except a resource (like a database or file handle). The following example illustrates encoding a PHP associative array into a JSON object:

<?php
// An associative array
$marks = array("Peter"=>65, "Harry"=>80, "John"=>78, "Clark"=>90);

echo json_encode($marks);
?>

The result of the above example would appear as follows:

{"Peter":65,"Harry":80,"John":78,"Clark":90}

Similarly, you can encode a PHP indexed array into a JSON array, like this:

<?php
// An indexed array
$colors = array("Red", "Green", "Blue", "Orange", "Yellow");

echo json_encode($colors);
?>

The result of the previous example will be:

["Red","Green","Blue","Orange","Yellow"]

You can also instruct the json_encode() function to convert a PHP indexed array into a JSON object using the JSON_FORCE_OBJECT option. Here's an example:

<?php
// An indexed array
$colors = array("Red", "Green", "Blue", "Orange");

echo json_encode($colors, JSON_FORCE_OBJECT);
?>

The result of the previous example will be:

{"0":"Red","1":"Green","2":"Blue","3":"Orange"}

As shown in the examples above, a non-associative array can be encoded either as an array or an object. However, an associative array is always encoded as an object.


Decoding JSON Data in PHP

Decoding JSON data is straightforward. You can utilize the PHP json_decode() function to convert a JSON encoded string into the appropriate PHP data type. The following example demonstrates how to decode or convert a JSON object into a PHP object.

<?php
// Store JSON data in a PHP variable
$json = '{"Peter":65,"Harry":80,"John":78,"Clark":90}';

var_dump(json_decode($json));
?>

The result of the previous example would appear as follows:

object(stdClass)#1 (4) { ["Peter"]=> int(65) ["Harry"]=> int(80) ["John"]=> int(78) ["Clark"]=> int(90) }

By default, the json_decode() function returns an object. However, you can optionally specify a second parameter, $assoc, which accepts a boolean value. When set to true, JSON objects are decoded into associative arrays. This parameter defaults to false. Here's an example:

<?php
// Store JSON data in a PHP variable
$json = '{"Peter":65,"Harry":80,"John":78,"Clark":90}';

var_dump(json_decode($json, true));
?>

The result of the previous example would be:

array(4) { ["Peter"]=> int(65) ["Harry"]=> int(80) ["John"]=> int(78) ["Clark"]=> int(90) }

Now, let's explore an example that demonstrates how to decode JSON data and access individual elements of the JSON object or array in PHP.

<?php
// Assign JSON encoded string to a PHP variable
$json = '{"Peter":65,"Harry":80,"John":78,"Clark":90}';

// Decode JSON data to PHP associative array
$arr = json_decode($json, true);
// Access values from the associative array
echo $arr["Peter"];  // Output: 65
echo $arr["Harry"];  // Output: 80
echo $arr["John"];   // Output: 78
echo $arr["Clark"];  // Output: 90

// Decode JSON data to PHP object
$obj = json_decode($json);
// Access values from the returned object
echo $obj->Peter;   // Output: 65
echo $obj->Harry;   // Output: 80
echo $obj->John;    // Output: 78
echo $obj->Clark;   // Output: 90
?>

You can iterate through the decoded data using a foreach() loop, as shown below:

<?php
// Assign JSON encoded string to a PHP variable
$json = '{"Peter":65,"Harry":80,"John":78,"Clark":90}';

// Decode JSON data to PHP associative array
$arr = json_decode($json, true);

// Loop through the associative array
foreach($arr as $key=>$value){
echo $key . "=>" . $value . "<br>";
}
echo "<hr>";
// Decode JSON data to PHP object
$obj = json_decode($json);

// Loop through the object
foreach($obj as $key=>$value){
echo $key . "=>" . $value . "<br>";
}
?>

Extracting Values from Nested JSON Data in PHP

JSON objects and arrays can also be nested. A JSON object can contain other JSON objects, arrays, nested arrays, arrays of JSON objects, and more. The next example demonstrates how to decode a nested JSON object and display all its values in PHP.

<?php
// Define recursive function to extract nested values
function printValues($arr) {
global $count;
global $values;

// Check input is an array
if(!is_array($arr)){
die("ERROR: Input is not an array");
}

/*
Loop through array, if value is itself an array recursively call the
function else add the value found to the output items array,
and increment counter by 1 for each value found
*/
foreach($arr as $key=>$value){
if(is_array($value)){
printValues($value);
} else{
$values[] = $value;
$count++;
}
}

// Return total count and values found in array
return array('total' => $count, 'values' => $values);
}

// Assign JSON encoded string to a PHP variable
$json = '{
"book": {
"name": "Harry Potter and the Goblet of Fire",
"author": "J. K. Rowling",
"year": 2000,
"characters": ["Harry Potter", "Hermione Granger", "Ron Weasley"],
"genre": "Fantasy Fiction",
"price": {
"paperback": "$10.40", "hardcover": "$20.32", "kindle": "4.11"
}
}
}';
// Decode JSON data into PHP associative array format
$arr = json_decode($json, true);

// Call the function and print all the values
$result = printValues($arr);
echo "<h3>" . $result["total"] . " value(s) found: </h3>";
echo implode("<br>", $result["values"]);

echo "<hr>";

// Print a single value
echo $arr["book"]["author"] . "<br>";  // Output: J. K. Rowling
echo $arr["book"]["characters"][0] . "<br>";  // Output: Harry Potter
echo $arr["book"]["price"]["hardcover"];  // Output: $20.32
?>