结构化JSON布局

Mac*_*Mac 5 php json

我目前正在使用PHP的JSON,当我编码它时,它将输出为:

{"username":"ND","email":"test@email.com","regdate":"8th June 2010","other":{"alternative":"ND"},"level":"6"}
Run Code Online (Sandbox Code Playgroud)

当我希望它输出像这样:

{
    "username": "ND",
    "email": "test@email.com",
    "regdate": "8th June 2010",
    "other":
    {
        "alternative": "ND"
    },
    "level":"6"
}
Run Code Online (Sandbox Code Playgroud)

因此,我和我的其他开发人员在结构化时可以很好地阅读它.我怎样才能做到这一点?

示例也是这样的:

https://graph.facebook.com/19292868552

干杯

Mat*_*hew 5

我自己也觉得这很有用,所以这里写的是一个小函数:

<?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;
}
?>
Run Code Online (Sandbox Code Playgroud)

这很天真,相信PHP会返回一个有效的JSON字符串.它可以更简洁地编写,但这种方式很容易修改.(当然,这会在只有机器读取文本的生产场景中增加不必要的开销.)

编辑:添加了一个else子句来捕获数字和其他未知字符.

  • 如果你认为在使用内置的JSON函数时相信PHP会产生JSON是天真的......你怎么能相信PHP足以使用它呢? (2认同)