/** * Indents a flat JSON string to make it more human-readable * * @param string $json The original JSON string to process * @return string Indented version of the original JSON string */ public static function indent($json) { $result = ''; $pos = 0; $strLen = strlen($json); $indentStr = ' '; $newLine = "\n"; for($i = 0; $i <= $strLen; $i++) { // Grab the next character in the string $char = substr($json, $i, 1); // If this character is the end of an element, // output a new line and indent the next line if($char == '}' || $char == ']') { $result .= $newLine; $pos --; for ($j=0; $j<$pos; $j++) { $result .= $indentStr; } } // Add the character to the result string $result .= $char; // If the last character was the beginning of an element, // output a new line and indent the next line if ($char == ',' || $char == '{' || $char == '[') { $result .= $newLine; if ($char == '{' || $char == '[') { $pos ++; } for ($j = 0; $j < $pos; $j++) { $result .= $indentStr; } } } return $result; }
Thank you man. This function very simple & usefull. Now i can easely read server json responses.
No problem, glad you found it useful!
Hi, I found this in Google and made a Smarty (see smarty.net) plugin out of it in about twenty seconds:
Thanks.
<?php
/* Taken from http://recurser.com/articles/2008/03/11/format-json-with-php/ */
/**
* Indents a flat JSON string to make it more human-readable
*
*
param string $json The original JSON string to processreturn string Indented version of the original JSON string*
*/
function smarty_modifier_formatjson($json) {
$result = ‘’;
$pos = 0;
$strLen = strlen($json);
$indentStr = ‘ ‘;
$newLine = “\n”;
for($i = 0; $i <= $strLen; $i ) {
// Grab the next character in the string
$char = substr($json, $i, 1);
// If this character is the end of an element,
// output a new line and indent the next line
if($char ‘}’ || $char ‘]’) {
$result .= $newLine;
$pos —;
for ($j=0; $j<$pos; $j ) {
$result .= $indentStr;
}
}
// Add the character to the result string
$result .= $char;
// If the last character was the beginning of an element,
// output a new line and indent the next line
if ($char ‘,’ || $char ‘{’ || $char ‘[‘) {
$result .= $newLine;
if ($char ‘{’ || $char == ‘[’) {
$pos ;
}
for ($j = 0; $j
There is an major issue with the code. It does not take into consideration string escaping.
If a string value (inside quotes) has ‘,’ (COMMA) in it, it simply puts a newline after it. When doing an eval, this will give an unterminated error.
Example input:
code”:”“}
Example output: (Note that in the value html an unwanted newline is added after COMMA.)
{
code”,
success,
params
part”,
entity”,
html”
}
}
The code may work for simple strings, however it will give unexpected errors for complex data in string values.
if their is “{[}]” chars in a string eements, theiy ar indented
exemple :
indent(‘a{23]”}’);
{
“a”:1,
“b”:”[
1{
}23
]”
}
This modified version will ignore special characters in quoted strings.
public static function indent($json) {
$result = ‘’;
$pos = 0;
$strLen = strlen($json);
$indentStr = ‘ ‘;
$newLine = “\n”;
for($i = 0; $i <= $strLen; $i ) {
// Grab the next character in the string
$char = substr($json, $i, 1);
// Skip quoted keys and values
if ($char '"' || $char "'") {
echo "Found $char at position $i";
$lookfor = $char;
for ($i = $i 1; $i <= $strLen; $i ) {
$result .= $char;
$char = substr($json, $i, 1);
if ($char == $lookfor) {
echo " and closing $char at $i";
break;
}
}
}
// If this character is the end of an element,
// output a new line and indent the next line
if($char '}' || $char ']') {
$result .= $newLine;
$pos —;
for ($j=0; $j<$pos; $j ) {
$result .= $indentStr;
}
}
// Add the character to the result string
$result .= $char;
// If the last character was the beginning of an element,
// output a new line and indent the next line
if ($char ',' || $char '{' || $char '[') {
$result .= $newLine;
if ($char '{' || $char == '[') {
$pos ;
}
for ($j = 0; $j < $pos; $j ) {
$result .= $indentStr;
}
}
}
return $result;
}
Hi Davev,
your Code from 2009/10/03 produces only errors if I copy/paste it. Could you Post it without all this typing errors? It would be very kind of you.
Thanks for the code, quite useful when you are lazy to do yourself :)
Thanks for this code. I’ve implemented some small enhancements:
- “$i < $strLen" instead of "$i <= $strLen" – Use $json as an Array instead of using substr – Cache the current $indention for better performance – Check for escaped sequenzes ("Strings") – Parameters $indentStr and $newLine as arguments – Parameter $json as reference
public static function indentJSON(& $json, $indentStr = “ “, $newLine = “\n”) {
$result = “”; // Resulting string
$indention = “”; // Current indention after newline
$pos = 0; // Indention width
$escaped = false; // FALSE or escape character
$strLen = strlen($json);
for($i = 0; $i < $strLen; $i ) {
// Grab the next character in the string
$char = $json[$i];
if ($escaped) {
if ($escaped $char) {
// End of escaped sequence
$escaped = false;
}
$result .= $char;
if ($char "\" && $i 1 < $strLen) {
// Next character will NOT end this sequence
$result .= $json[ $i];
}
continue;
}
if ($char '"' || $char "'") {
// Escape this string
$escaped = $char;
$result .= $char;
continue;
}
// If this character is the end of an element,
// output a new line and indent the next line
if($char '}' || $char ']') {
$indention = str_repeat($indentStr, —$pos);
$result .= $newLine . $indention;
}
// Add the character to the result string
$result .= $char;
// If the last character was the beginning of an element,
// output a new line and indent the next line
if ($char ',' || $char '{' || $char '[') {
if ($char '{' || $char == '[') {
$indention = str_repeat($indentStr, $pos);
}
$result .= $newLine . $indention;
}
}
return $result;
}
Whoops, seems that some characters got filtered by this comment form. See http://dau-sicher.de/stuff/indentJSON.inc.phps for an unfiltered version.