Pretty-Printing JSON with PHP

后端 未结 24 1834
一向
一向 2020-11-22 02:03

I\'m building a PHP script that feeds JSON data to another script. My script builds data into a large associative array, and then outputs the data using json_encode

24条回答
  •  甜味超标
    2020-11-22 03:00

    This solution makes 'really pretty' JSON. Not exactly what the OP was asking for, but it lets you visualise the JSON better.

    /**
     * takes an object parameter and returns the pretty json format.
     * this is a space saving version that uses 2 spaces instead of the regular 4
     *
     * @param $in
     *
     * @return string
     */
    function pretty_json ($in): string
    {
      return preg_replace_callback('/^ +/m',
        function (array $matches): string
        {
          return str_repeat(' ', strlen($matches[0]) / 2);
        }, json_encode($in, JSON_PRETTY_PRINT | JSON_HEX_APOS)
      );
    }
    
    /**
     * takes a JSON string an adds colours to the keys/values
     * if the string is not JSON then it is returned unaltered.
     *
     * @param string $in
     *
     * @return string
     */
    
    function markup_json (string $in): string
    {
      $string  = 'green';
      $number  = 'darkorange';
      $null    = 'magenta';
      $key     = 'red';
      $pattern = '/("(\\\\u[a-zA-Z0-9]{4}|\\\\[^u]|[^\\\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/';
      return preg_replace_callback($pattern,
          function (array $matches) use ($string, $number, $null, $key): string
          {
            $match  = $matches[0];
            $colour = $number;
            if (preg_match('/^"/', $match))
            {
              $colour = preg_match('/:$/', $match)
                ? $key
                : $string;
            }
            elseif ($match === 'null')
            {
              $colour = $null;
            }
            return "{$match}";
          }, str_replace(['<', '>', '&'], ['<', '>', '&'], $in)
       ) ?? $in;
    }
    
    public function test_pretty_json_object ()
    {
      $ob       = new \stdClass();
      $ob->test = 'unit-tester';
      $json     = pretty_json($ob);
      $expected = <<assertEquals($expected, $json);
    }
    
    public function test_pretty_json_str ()
    {
      $ob   = 'unit-tester';
      $json = pretty_json($ob);
      $this->assertEquals("\"$ob\"", $json);
    }
    
    public function test_markup_json ()
    {
      $json = <<"name": "abc",
        "id": 123,
        "warnings": [],
        "errors": null
      },
      {
        "name": "abc"
      }
    ]
    STR;
    
      $output = markup_json(pretty_json(json_decode($json)));
      $this->assertEquals($expected,$output);
    }
    

    }

提交回复
热议问题