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. 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.
$_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);
}
链接地址: http://www.djcxy.com/p/47286.html
上一篇: 从用foreach循环构建的JSON中删除最后一个逗号
下一篇: 漂亮的打印JSON不起作用