Skip to content
brianburwell11 edited this page Jun 21, 2022 · 7 revisions

Module prettierjson

prettierjson

made-with-python Code style: black Github release PyPi Documentation

Generate prettier and more compact JSON dumps

Installation

prettierjson can be installed using one of these commands:

pip install prettierjson
poetry add prettierjson

Usage

in python scripts

prettierjson offers one function prettierjson.dumps() which is intended to be used as a drop-in replacement for json.dumps()

from prettierjson import dumps

my_dictionary = {"foo": bar}

with open("foobar.json", "w") as f:
    f.write(dumps(my_dictionary))

If prettierjson needs to exist within the same module as the built-in json package without overriding the default json.dumps(), the entire package should be imported in order to avoid namespace collisions

import json
import prettierjson

my_dictionary = {"foo": bar}

with open("builtin.json", "w") as f:
    f.write(json.dumps(my_dictionary))
with open("prettierjson.json", "w") as f:
    f.write(prettierjson.dumps(my_dictionary))

See the documentation for more details.

as a command line interface

prettierjson has a __main__ module which allows it to be called directly when installed with the command python -m prettierjson.

In this way, prettierjson can be used to "prettify" one or multiple JSON files in-place by passing them as arguments

$ python -m prettierjson PATH/TO/JSON/FILE1.json PATH/TO/JSON/FILE2.json

Indent size and max line length can be set with the --indent and --line-length flags

$ python -m prettierjson --indent=2 --line-length=88 PATH/TO/JSON/FILE.json

Run python -m prettierjson -h for more command line usage details.

Sub-modules

  • prettierjson.prettierjson

Functions

dumps(obj, indent=4, max_line_length=80) : Renders JSON content with indentation and line splits/concatenations to fit max_line_length.

Only dicts, lists and basic types are supported

Parameters
----------
obj : dict, list, tuple, str
    A python object to be converted to JSON
indent : int, optional
    How many spaces to use as an indent before nested keys. Default is 2
max_line_length : int, optional
    How many characters to limit a single line to before wrapping to the next line. Default is 80 characters

Returns
-------
str
    A representation of the JSON to be piped to a .json file

Clone this wiki locally