Tag: PHP json

jsonの整形

function jsonCnv($json)
{
    $def = array(
        '/([{\[,])/'        => "$1\n",
        '/([}\]])/'         => "\n$1",
        '/([^\s]):([^\s])/' => '$1 : $2',
    );

    $p = array_keys($def);
    $r = array_values($def);
    $s = preg_replace($p, $r, $json);

    $buf    = explode("\n", $s);
    $indent = 0;
    $out    = array();
    foreach ($buf as $line) {
        if (preg_match('/[}\]],?$/', $line)) {
            $indent--;
        }
        $out[] = str_repeat("\t", $indent) . $line;
        if (preg_match('/[{\[]$/', $line)) {
            $indent++;
        }
    }

    return implode("\n", $out);
}

Last-modified: 2011-08-02 (火) 12:00:09 (2270d)