How to Prettyprint a Json File

How to prettyprint a JSON file?

The json module already implements some basic pretty printing in the dump and dumps functions, with the indent parameter that specifies how many spaces to indent by:

>>> import json
>>>
>>> your_json = '["foo", {"bar":["baz", null, 1.0, 2]}]'
>>> parsed = json.loads(your_json)
>>> print(json.dumps(parsed, indent=4, sort_keys=True))
[
"foo",
{
"bar": [
"baz",
null,
1.0,
2
]
}
]

To parse a file, use json.load():

with open('filename.txt', 'r') as handle:
parsed = json.load(handle)

Pretty-Print JSON Data to a File using Python

You should use the optional argument indent.

header, output = client.request(twitterRequest, method="GET", body=None,
headers=None, force_auth_header=True)

# now write output to a file
twitterDataFile = open("twitterData.json", "w")
# magic happens here to make it pretty-printed
twitterDataFile.write(simplejson.dumps(simplejson.loads(output), indent=4, sort_keys=True))
twitterDataFile.close()

How can I pretty-print a JSON file from the command line?

Pipe the results from the file into the python json tool 2.6 onwards

python -m json.tool < 'file_name'

Pretty-Print JSON in Java

Google's GSON can do this in a nice way:

Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(uglyJsonString);
String prettyJsonString = gson.toJson(je);

or since it is now recommended to use the static parse method from JsonParser you can also use this instead:

Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonElement je = JsonParser.parseString​(uglyJsonString);
String prettyJsonString = gson.toJson(je);

Here is the import statement:

import com.google.gson.*;

Here is the Gradle dependency:

implementation 'com.google.code.gson:gson:2.8.7'

How can I pretty-print JSON using Go?

Writing JSON file with pretty print

As Nivas said in the comments, some programs strip newlines, so viewing the output in those programs (such as Notepad) could make them look "ugly". Make sure you are viewing them in a program that displays newlines correctly, such as Notepad++.

Pretty Print a json file when returning in a flask function

There is a config option JSONIFY_PRETTYPRINT_REGULAR which allows you to do this.

from flask import Flask, jsonify
import flask
import json

app = Flask(__name__)
app.config["JSONIFY_PRETTYPRINT_REGULAR"] = True

with open('VO/IFATC EG/qotd.json') as qotd_file:
data = json.load(qotd_file)

rr = data['questions']
car = json.dumps(data, indent=4)
print(car)

@app.route('/')
def words():
return jsonify(data)

app.run()

Note that the return uses jsonify instead of json.dumps.

pretty-print JSON using JavaScript

Pretty-printing is implemented natively in JSON.stringify(). The third argument enables pretty printing and sets the spacing to use:

var str = JSON.stringify(obj, null, 2); // spacing level = 2

If you need syntax highlighting, you might use some regex magic like so:

function syntaxHighlight(json) {
if (typeof json != 'string') {
json = JSON.stringify(json, undefined, 2);
}
json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
var cls = 'number';
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key';
} else {
cls = 'string';
}
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
}
return '<span class="' + cls + '">' + match + '</span>';
});
}

See in action here: jsfiddle

Or a full snippet provided below:

function output(inp) {    document.body.appendChild(document.createElement('pre')).innerHTML = inp;}
function syntaxHighlight(json) { json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>'); return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) { var cls = 'number'; if (/^"/.test(match)) { if (/:$/.test(match)) { cls = 'key'; } else { cls = 'string'; } } else if (/true|false/.test(match)) { cls = 'boolean'; } else if (/null/.test(match)) { cls = 'null'; } return '<span class="' + cls + '">' + match + '</span>'; });}
var obj = {a:1, 'b':'foo', c:[false,'false',null, 'null', {d:{e:1.3e5,f:'1.3e5'}}]};var str = JSON.stringify(obj, undefined, 4);
output(str);output(syntaxHighlight(str));
pre {outline: 1px solid #ccc; padding: 5px; margin: 5px; }.string { color: green; }.number { color: darkorange; }.boolean { color: blue; }.null { color: magenta; }.key { color: red; }


Related Topics



Leave a reply



Submit