JSON structured layout

I am working with JSON with PHP at the moment, when I encode it, it will be output as:

{"username":"ND","email":"test@email.com","regdate":"8th June 2010","other":{"alternative":"ND"},"level":"6"}

When I want it to be output as follows:

{
    "username": "ND",
    "email": "test@email.com",
    "regdate": "8th June 2010",
    "other":
    {
        "alternative": "ND"
    },
    "level":"6"
}

So that I and my other developers can read it well when they are structured. How can i do this?

An example also looks like this:

https://graph.facebook.com/19292868552

Greetings

+5
source share
4 answers

I could find this useful myself, so here is a small function that I wrote:

<?php
function json_pretty_encode($obj)
{
 $json = json_encode($obj);
 if (!$json) return $json;

 $f = '';
 $len = strlen($json);

 $depth = 0;
 $newline = false;

 for ($i = 0; $i < $len; ++$i)
 {
  if ($newline)
  {
   $f .= "\n";
   $f .= str_repeat(' ', $depth);
   $newline = false;
  }

  $c = $json[$i];
  if ($c == '{' || $c == '[')
  {
   $f .= $c;
   $depth++;
   $newline = true;
  }
  else if ($c == '}' || $c == ']')
  {
   $depth--;
   $f .= "\n";
   $f .= str_repeat(' ', $depth);
   $f .= $c;
  }
  else if ($c == '"')
  {
   $s = $i;
   do {
    $c = $json[++$i];
    if ($c == '\\')
    {
     $i += 2;
     $c = $json[$i];
    }
   } while ($c != '"');
   $f .= substr($json, $s, $i-$s+1);
  }
  else if ($c == ':')
  {
   $f .= ': ';
  }  
  else if ($c == ',')
  {
   $f .= ',';
   $newline = true;
  }
  else
  {
   $f .= $c;
  }
 }

 return $f;
}
?>

, , PHP JSON. , . (, , , .)

: else, .

+5

PHP 5.4.0 Alpha1, :

$data = array (
  'username' => 'ND',
  'email' => 'test@email.com',
  'regdate' => '8th June 2010',
  'other' =>
  array (
    'alternative' => 'ND',
  ),
  'level' => '6',
);

echo json_encode($data, JSON_PRETTY_PRINT),"\n";

:

{
    "username": "ND",
    "email": "test@email.com",
    "regdate": "8th June 2010",
    "other": {
        "alternative": "ND"
    },
    "level": "6"
}
+3

you can also try installing the json_xs tool and use it in tandem with curl: curl -X GET http://some.re/sour/se/name.json | json_xs

0
source

This is probably the easiest way:

var_dump(json_decode($json));
-2
source

All Articles