1

I am trying to pretty print JSON currently in PHP, I have looked at the threads like Pretty-Printing JSON with PHP this but it does not work. I am on PHP 7.0.8-0ubuntu0.16.04.3

Code:

<form method="POST">
    <textarea name="json_data" id="json_data">
        <?php
            if(isset($_POST['json_data'])){
                echo json_encode($_POST['json_data'], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
            }
        ?>
    </textarea>

    <input type="submit" value="Pretty Print JSON">
</form>

Output:

"[{\"title\":\"The Chainsmokers - Closer (Lyric) ft. Halsey\",\"length\":262000,\"id\":\"PT2_F-1esPk\",\"requester\":\"158310004187725824\",\"guildId\":\"226785954537406464\"}]"

Input JSON

[{"title":"The Chainsmokers - Closer (Lyric) ft. Halsey","length":262000,"id":"PT2_F-1esPk","requester":"158310004187725824","guildId":"226785954537406464"}]

For some reason the options JSON_PRETTY_PRINT and JSON_UNESCAPED_SLASHES do not actually work. Why is that? These are from PHP 5.4 and I am on PHP 7.

Don't Panic
  • 41,125
  • 10
  • 61
  • 80
Walshy
  • 850
  • 2
  • 11
  • 32

1 Answers1

5

$_POST['json_data'] is already a JSON string, so you're encoding something that's already encoded; this basically just escapes all the double quotes inside the string, and wraps quotes around the result. You need to decode it first, then encode the result with pretty-printing.

if (isset($_POST['json_data'])) {
    $data = json_decode($_POST['json_data']);
    echo json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
}
Barmar
  • 741,623
  • 53
  • 500
  • 612