简体   繁体   English

漂亮的打印JSON无法正常工作

[英]Pretty printing JSON isn't working

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. 我正在尝试在PHP中漂亮地打印JSON,我查看了类似PHP的Pretty-Printing JSON这样的线程但是它不起作用。 I am on PHP 7.0.8-0ubuntu0.16.04.3 我在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 输入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. 由于某些原因,选项JSON_PRETTY_PRINTJSON_UNESCAPED_SLASHES实际上不起作用。 Why is that? 这是为什么? These are from PHP 5.4 and I am on PHP 7. 这些来自PHP 5.4,我使用PHP 7。

$_POST['json_data'] is already a JSON string, so you're encoding something that's already encoded; $_POST['json_data']已经是一个JSON字符串,因此您正在编码已经编码的东西; 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM