PHP Manual
/
Data structures

Json in PHP - processing, generation and formatting

26. 11. 2019

Obsah článku

The Json data format was created to facilitate the transfer of structured data between client and server.

Converting an array or object to json

To convert an array or object to Json, there is a function json_encode in PHP:

$user = [
'name' => 'Jan',
'surname' => 'Barasek',
'role' => [
'admin',
'moderator',
],
];
echo json_encode($user);

Generates:

{"name": "Jan", "surname": "Barasek", "role":["admin", "moderator"]}

The json_encode() function can also convert other data types. For example, we can directly insert integer (integer), string (string) and so on.

Json pretty print - better human readability

In the default configuration, json is generated as one long string. This is for the reason to take up as little space as possible.

If you require better human readability, just pass the JSON_PRETTY_PRINT constant as the second parameter:

echo json_encode($users, JSON_PRETTY_PRINT);

Generates:

{
"name": "jan",
"surname": "Barasek",
"role": [
"admin",
"moderator".
]
}

Formatting json - custom formatting rules

The normal formatting of json via PHP has no additional settings and we have to be satisfied with this output only. For example, if we want to indent tabs instead of spaces (or modify the generation rules in any way), we have to program it ourselves.

This function can already do basic formatting and we just need to modify it:

function prettyJsonPrint(string $json): string
{
$result = '';
$level = 0;
$in_quotes = false;
$in_escape = false;
$ends_line_level = NULL;
$json_length = strlen($json);
for ($i = 0; $i < $json_length; $i++) {
$char = $json[$i];
$new_line_level = NULL;
$post = '';
if ($ends_line_level !== NULL) {
$new_line_level = $ends_line_level;
$ends_line_level = NULL;
}
if ($in_escape) {
$in_escape = false;
} else if ($char === '"') {
$in_quotes = !$in_quotes;
} else if (!$in_quotes) {
switch ($char) {
case '}':
case ']':
$level--;
$ends_line_level = NULL;
$new_line_level = $level;
break;
case '{':
case '[':
$level++;
case ',':
$ends_line_level = $level;
break;
case ':':
$post = ' ';
break;
case " ":
case "\t":
case "\n":
case "\r":
$char = '';
$ends_line_level = $new_line_level;
$new_line_level = NULL;
break;
}
} else if ($char === '\\') {
$in_escape = true;
}
if ($new_line_level !== NULL) {
$result .= "\n" . str_repeat("\t", $new_line_level);
}
$result .= $char . $post;
}
return $result;
}

Source : https://stackoverflow.com/questions/6054033/pretty…

For example, input:

{"key1":[1,2,3],"key2":"value"}

Formatted as:

{
"key1": [
1,
2,
3
],
"key2": "value"
}

Which is much easier to read (because of the consistent indentation of each element).

Coloring json notation as HTML

Sometimes it can be useful to color highlight keys, the data itself, and individual formatting elements (especially closing brackets).

For example, input:

{"access": {"token": {"issued_at": "2008-08-16T14:10:31.309353", "expires": "2008-08-17T14:10:31Z", "id": "MIICQgYJKoZIhvcIegeyJpc3N1ZWRfYXQiOiAi"}, "serviceCatalog": [], "user": {"username": "ajay", "roles_links": [], "id": "16452ca89", "roles": [], "name": "ajay"}}}

Formatted as:

{
  "access": {
   "token": {
      "issued_at""2008-08-16T14:10:31.309353"
     "expires""2008-08-17T14:10:31Z"
     "id""MIICQgYJKoZIhvcIegeyJpc3N1ZWRfYXQiOiAi"
    },
   "serviceCatalog": [
   ], 
   "user": {
     "username""ajay"
    "roles_links": [
     ], 
     "16452ca89"
    "roles": [
     ], 
     "name""ajay"
    }
  }
}

This can be implemented by the following function:

function jsonColorFormater(string $json, string $indentation = "\t"): string
{
$crl = 0;
$ss = false;
$buffer = '';
for ($c = 0; $c < strlen($json); $c++) {
if ($json[$c] == '}' || $json[$c] == ']') {
$crl--;
$buffer .= "\n" . str_repeat($indentation, $crl);
}
if ($json[$c] == '"' && (@$json[$c - 1] == ',' || @$json[$c - 2] == ',') {
$buffer .= "\n" . str_repeat($indentation, $crl);
}
if ($json[$c] == '"' && !$ss) {
$buffer .= '<span style="color:'.((@$json[$c - 1] == ':' || @$json[$c - 2] == ':') ? '#35D' : '#C22').';">';
}
$buffer .= $json[$c];
if ($json[$c] == '"' && $ss) $buffer .= '</span>';
if ($json[$c] == '"') $ss = !
if ($json[$c] == '{' || $json[$c] == '[') {
$crl++;
$buffer .= "\n". str_repeat($indentation, $crl);
}
}
// Returns the HTML source
return '<pre>' . $buffer . '</pre>';
}
// Just call this and it will return formatted output
// echo jsonColorFormater($data, ' ');

Function taken and radically rewritten from: https://stackoverflow.com/a/20953262/6777550

Convert from JSON to PHP array/object

This can be implemented with the json_decode() function, which makes a data structure out of Json that we need to work with as an object:

$json = '{"name": "Jan", "surname": "Barasek", "role":["admin", "moderator"]}';
$decode = json_decode($json);
echo $decode->name; // Returns 'Jan'
// echo $decode->role;
//
// This doesn't work because property role
// contains an array, we have to iterate.
echo '<ul>';
foreach ($decode->role as $role) {
echo '<li>' . $role . '</li>'; // Sequentially lists the roles after the bullets
}
echo '</ul>';

Processing in javascript

For example, in the jQuery library, a json string can be parsed into an object very easily:

var json = '{"name": "Jan", "surname": "Barasek", "role":["admin", "moderator"]}';
var parser = $.parseJSON(json);
document.write('Name: ' + parser.name);
console.log(parser); // Prints the entire object to the console for debugging

In javascript, in general, any json is a valid javascript object that can be worked with directly and its properties accessed.

Jan Barášek   Více o autorovi

Autor článku pracuje jako seniorní vývojář a software architekt v Praze. Navrhuje a spravuje velké webové aplikace, které znáte a používáte. Od roku 2009 nabral bohaté zkušenosti, které tímto webem předává dál.

Rád vám pomůžu:

Související články

1.
Status:
All systems normal.
2024