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.

Pretty printing of JSON using PHP and Javascript by Anil Kumar Panigrahi

Pretty printing of JSON using PHP and Javascript by Anil Kumar Panigrahi

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:

1
<pre id="json"></pre>

Completed code using Javascript:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!DOCTYPE html>

<html>

<head>
        <title>JSON Formatter</title>
</head>

<body>
<pre id="json"></pre>

<script>

    var data = [{"Product":{"name":"iPhone","series":"x","price":"$100.00"}}]
    document.getElementById("json").innerHTML = JSON.stringify(data, undefined, 2);

</script>

</body>
</html>

Readable pretty format using PHP

HTML form code:

1
2
3
4
<form action="" method="POST">
        <textarea name="json_text" style="width: 500px; height: 200px;"></textarea>
        <input type="submit" />
</form>

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

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *