How to Decode a JSON String in PHP

From WikiHTP

JSON (JavaScript Object Notation) is a platform and language independent way of serializing objects into plaintext. Because it is often used on the web and so is PHP, there is a basic extension for working with JSON in PHP. Here we are about to see how to decode a JSON string in PHP.

Decoding a JSON String[edit]

The json_decode() function takes a JSON-encoded string as its first parameter and parses it into a PHP variable.

Normally, json_decode() will return an object of \stdClass if the top level item in the JSON object is a dictionary or an indexed array if the JSON object is an array. It will also return scalar values or NULL for certain scalar values, such as simple strings, "true", "false", and "null". It also returns NULL on any error.

// Returns an object (The top level item in the JSON string is a JSON dictionary)
$json_string = '{"name": "Jeff", "age": 20, "active": true, "colors": ["red", "blue"]}';
$object = json_decode($json_string);
printf('Hello %s, You are %s years old.', $object->name, $object->age);
#> Hello Jeff, You are 20 years old.

// Returns an array (The top level item in the JSON string is a JSON array)
$json_string = '["Jeff", 20, true, ["red", "blue"]]';
$array = json_decode($json_string);
printf('Hello %s, You are %s years old.', $array[0], $array[1]);

Use var_dump() to view the types and values of each property on the object we decoded above.

// Dump our above $object to view how it was decoded
var_dump($object);

Output (note the variable types):

class stdClass#2 (4) {
 ["name"] => string(4) "Jeff"
 ["age"] => int(20)
 ["active"] => bool(true)
 ["colors"] =>
   array(2) {
     [0] => string(3) "red"
     [1] => string(4) "blue"
   }
}

Note: The variable types in JSON were converted to their PHP equivalent.

Array Output[edit]

Decoding a JSON String will also return as Array. To return an associative array for JSON objects instead of returning an object, pass true as the second parameter to json_decode().

$json_string = '{"name": "Jeff", "age": 20, "active": true, "colors": ["red", "blue"]}';
$array = json_decode($json_string, true); // Note the second parameter
var_dump($array);

Output (note the array associative structure):

array(4) {
  ["name"] => string(4) "Jeff"
  ["age"] => int(20)
  ["active"] => bool(true)
  ["colors"] =>
  array(2) {
    [0] => string(3) "red"
    [1] => string(4) "blue"
  }
}

The second parameter ($assoc) has no effect if the variable to be returned is not an object.

Note: If you use the $assoc parameter, you will lose the distinction between an empty array and an empty object. This means that running json_encode() on your decoded output again, will result in a different JSON structure.

Related[edit]

About This Tutorial

This page was last edited on 28 January 2019, at 07:34.