Easier Reading of JSON Data
When JSON data is converted into an array, the information in the data generally is easier to read.
(JSON is a popular data-exchange format. A data-exchange format can be used to transmit data objects, which is data composed of lists and/or as name-value pairs.)
An example of use is within MySQL tables. It may be the easiest way to store data objects that is currently available for PHP. The data is read from the MySQL table, decoded, and used. If the data is changed, it is formatted back to JSON and stored in the MySQL table.
JSON data is somewhat readable. If you only need an idea of what it's about, then generally it can be gleaned from the raw data.
Here is an illustration.
{"colors":{"preferred-house-color":"white","house-color-selections":["red","blue","yellow","white","tan"],"preferred-sky-color":"blue","sky-color-selections":["blue","gray"]}}
To make it more readable (although still not like a paragraph of text) JSON data can be converted into an array.
How much more readable depends on your experience reading arrays. Even with no previous experience, the array would be easier to read.
Here is the above JSON converted into an array. Both the following array and the above JSON contain the same information.
Array ( [colors] => Array ( [preferred-house-color] => white [house-color-selections] => Array ( [0] => red [1] => blue [2] => yellow [3] => white [4] => tan ) [preferred-sky-color] => blue [sky-color-selections] => Array ( [0] => blue [1] => gray ) ) )
As you can see, it is more readable.
The following PHP script can be used to convert JSON data into an array.
<?php
// Paste the JSON between the two lines containing BEGINENDMARKER
// The multi-line JSON is acceptable so long as it is properly formatted.
$JSON = <<<BEGINENDMARKER
{"colors":{"preferred-house-color":"white","house-color-selections":["red","blue","yellow","white","tan"],"preferred-sky-color":"blue","sky-color-selections":["blue","gray"]}}
BEGINENDMARKER;
// To remove any leading or trailing white space.
$JSON = trim($JSON);
// Convert to array.
$Jarray = json_decode($JSON,true);
// Print the array to the screen.
echo '<pre>'.print_r($Jarray,true).'</pre>';
?>
Save the above as json2array.php
or other *.php
file name. Upload the script to your server and note its URL.
To use:
Replace the blue JSON data with your own JSON data.
Type the
json2array.php
URL into your browser.
The json2array.php
converts JSON data into an array and prints it on the screen. The array generally is more readable than it was as JSON data.
(This content first appeared in Possibilities newsletter.)
Will Bontrager