In this post, I would like to explain how to display JSON data in a pretty way. In the earlier posts, I have explained how to create API. This post is extended to display JSON, so that easy to understand and readable. To print the JSON data pretty way we have two approaches, we can use PHP and We can use Javascript.
Readable pretty format using Javascript
Javascript code:
1 2 3 4 5 | <script> var data = [{"Product":{"name":"iPhone","series":"x","price":"$100.00"}}] document.getElementById("json").innerHTML = JSON.stringify(data, undefined, 2); </script> |
HTML code:
Completed code using Javascript:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
Readable pretty format using PHP
HTML form code:
1 2 3 4 |
PHP code:
Read that textarea text and display as readable format
1 2 3 4 5 6 7 8 9 10 | <?php $json = ''; if (isset($_POST['json_text']) && !empty($_POST['json_text'])) { $struct = json_decode($_POST['json_text'], true); $json = json_encode($struct, JSON_PRETTY_PRINT); header('Content-Type: text/plain'); echo $json; exit; } ?> |
In earlier I have explained PHP headers, so in this I have used ‘text/plain’.
Complete code using PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | <?php $json = ''; if (isset($_POST['json_text']) && !empty($_POST['json_text'])) { $struct = json_decode($_POST['json_text'], true); $json = json_encode($struct, JSON_PRETTY_PRINT); header('Content-Type: text/plain'); echo $json; exit; } ?> <!DOCTYPE html> <html> <head> <title>JSON Formatter by Anil Labs</title> </head> <body> <div> <strong>Enter your non formated json in here and click submit to get pretty readable json!</strong> </div> <form action="" method="POST"> <textarea name="json_text" style="width: 500px; height: 200px;"></textarea> <input type="submit" /> </form> </body> </html> |
Hope it will use when we working on API documentation.
0 Comments