Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Human Readable JSON: aka Add spaces and breaks to json dump

Tags:

json

php

var-dump

Is there a "simple" script somewhere that will take a json data and format it to make it more readable?

For example:

// $response is a json encoded string.
var_dump($response);

The above outputs everything on one line. I'd like for it to be indented and spaced to make it easier to read.

like image 663
kylex Avatar asked Sep 12 '11 20:09

kylex


People also ask

How do you indent a JSON object?

We can use the indent parameter of json. dump() to specify the indentation value. By default, when you write JSON data into a file, Python doesn't use indentations and writes all data on a single line, which is not readable. The separator parameter: You can specify any separator between JSON key and value.

How do you remove spaces from a JSON file in Python?

Use the separators keyword argument to use the json. dumps() method without spaces, e.g. json_str = json. dumps(employee, separators=(',', ':')) . The separators argument can be set to a tuple containing a comma and a colon to remove the whitespace.

What is JSON encoding?

JSON (JavaScript Object Notation, pronounced /ˈdʒeɪsən/; also /ˈdʒeɪˌsɒn/) is an open standard file format and data interchange format that uses human-readable text to store and transmit data objects consisting of attribute–value pairs and arrays (or other serializable values).

How do I write a JSON file?

First, to write data to a JSON file, we must create a JSON string of the data with JSON. stringify . This returns a JSON string representation of a JavaScript object, which can be written to a file.


2 Answers

Note that var_dump and its terser cousin var_export do print newlines.

Bear in mind that newlines are not shown in HTML document by default. In an HTML context, you want this instead:

echo '<div style="font-family: monospace; white-space:pre;">';
echo htmlspecialchars(var_export($response));
echo '</div>';

In php 5.4+, you can simply use the PRETTY_PRINT flag of json_encode:

echo json_encode($response, JSON_PRETTY_PRINT);

Again, in an HTML context, you'll have to wrap it as described above.

like image 172
phihag Avatar answered Nov 16 '22 01:11

phihag


Paste it into JSONLint.com and click validate.

like image 32
AlienWebguy Avatar answered Nov 16 '22 02:11

AlienWebguy