This tutorial covers the fundamental particulars of the PHP json_encode operate. It provides examples of decoding JSON string enter to a PHP array.
It additionally describes this PHP JSON operate‘s conventions, guidelines and limitations. First, let’s see a fast instance of changing JSON to an array.
Convert JSON to PHP Array
This instance has a JSON string that maps the animal with its rely. The output of changing this JSON will return an associative array.
It makes use of PHP json_decode() with boolean true as its second parameter. With these decoding params, the JSON might be transformed right into a PHP array.
Fast instance
<?php
// JSON string in PHP Array
$jsonString = '{"Lion":101,"Tiger":102,"Crocodile":103,"Elephant":104}';
$phpArray = json_decode($jsonString, true);
// show the transformed PHP array
var_dump($phpArray);
?>
Output
array(4) {
["Lion"]=>
int(101)
["Tiger"]=>
int(102)
["Crocodile"]=>
int(103)
["Elephant"]=>
int(104)
}
See this on-line demo to get the transformed array consequence from a JSON enter.
View demo
See the diagram that exhibits the enter JSON string and the output stdClass object of the JSON decoding. Within the earlier article, now we have seen examples of the reverse operation that’s changing a PHP array to a JSON string.
PHP json_decode()
This native PHP operate decodes the JSON string right into a parsable object tree or an array. That is the syntax of this operate.
json_decode(
string $json,
?bool $associative = null,
int $depth = 512,
int $flags = 0
): combined
- $json – Enter JSON string.
- $associative – a boolean primarily based on which the output format varies between an associative array and a stdClass object.
- $depth – the allowed nesting restrict.
- $flag – Predefine constants to allow options like exception dealing with through the JSON to array convert.
You’ll find extra about this operate within the official documentation on-line.
Convert JSON to PHP Object
This program has a minute change of not setting the boolean flag to the PHP json_decode operate. This can return a PHP stdClass object tree as a substitute of an array.
<?php
// JSON string in PHP Array
$jsonString = '{"title":"Lion"}';
$phpObject = json_decode($jsonString);
print $phpObject->title;
?>
Output
Lion
Frequent errors throughout conversion from JSON to Array
The next JSON string is a sound JSON object in JavaScript, however not right here in PHP. The problem is the only quote. It ought to be modified to a double quote.
If you wish to see the JavaScript instance to learn and show JSON knowledge the linked article has the code.
<?php
// 1. key and worth ought to be inside double quotes
$notValidJson = "{ 'lion': 'animal' }";
json_decode($notValidJson); // will return null
// 2. and not using a quote can also be not allowed
$notValidJson = '{ lion: "animal" }';
json_decode($notValidJson); // will return null
// 3. shouldn't have a comma on the finish
$notValidJson = '{ "lion": "animal", }';
json_decode($notValidJson); // will return null
?>
Learn how to convert JSON with giant integers
This may be achieved by setting the bitmask parameter of the predefined JSON constants.
The JSON_BIGINT_AS_STRING fixed is used to transform JSON with knowledge having giant integers.
<?php
$jsonString = '{"largeNumber": 12345678901234567890123}';
var_dump(json_decode($jsonString, false, 512, JSON_BIGINT_AS_STRING));
?>
Output
object(stdClass)#1 (1) {
["number"]=>
string(20) "12345678901234567890123"
}
Learn how to get errors when utilizing json_decode
The operate json_last_error() is used to return particulars concerning the final error prevalence. The next instance handles the attainable error instances of this PHP JSON operate.
<?php
$jsonString = '{"Lion":101,"Tiger":102,"Crocodile":103,"Elephant":104}';
json_decode($jsonString);
swap (json_last_error()) {
case JSON_ERROR_DEPTH:
echo 'Error: Nesting restrict exceeded.';
break;
case JSON_ERROR_STATE_MISMATCH:
echo 'Error: Modes mismatch.';
break;
case JSON_ERROR_CTRL_CHAR:
echo 'Error: Surprising character discovered.';
break;
case JSON_ERROR_SYNTAX:
echo 'Error: Syntax error, invalid JSON.';
break;
case JSON_ERROR_UTF8:
echo 'Error: UTF-8 characters incorrect encoding.';
break;
default:
echo 'Surprising error.';
break;
}
?>
SURPRISE! JSON to Array and Array to JSON conversion shouldn’t be symmetrical
<?php
$jsonString = '{"0": "No", "1": "Sure"}';
// convert json to an associative array
$array = json_decode($jsonString, true);
print json_encode($array) . PHP_EOL;
?>
Output
["No","Yes"]
The PHP object is now modified to a PHP array. It’s possible you’ll not count on it.
Encode -> Decode -> Encode
The above is not going to return the info to its unique kind.
The output of decoding to PHP arrays and encoding from PHP arrays are usually not all the time symmetrical. However, the output of decoding from stdClass objects and encoding to stdClass objects are all the time symmetrical.
So when you’ve got plans to do cyclical conversion between the PHP array and a JSON string, then first convert the PHP array to an object. The convert the JSON.