Compact JSON Formatter

1.8.2 · deprecated · verified Thu Apr 16

compact-json is a Python library that provides a configurable JSON formatter, producing compact yet human-readable output. It is a pure Python port of FracturedJsonJs. As of its latest version, 1.8.2, the package is deprecated, and users are strongly encouraged to migrate to the `fractured-json` library, which directly tracks the original FracturedJson .NET assembly. The library is currently in maintenance mode with no further development planned.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates basic usage of the `Formatter` class to serialize a Python dictionary into a compact JSON string with custom formatting options. The example uses a simple dictionary and prints the formatted output to the console.

import json
from compact_json import Formatter, EolStyle

# Example Python dictionary
data = {
    "widget": {
        "debug": "on",
        "window": {"title": "Sample Widget", "name": "main_window", "width": 500, "height": 500},
        "image": {"src": "Images/Sun.png", "name": "sun1", "hOffset": 250, "vOffset": 250, "alignment": "center"},
        "text": {
            "data": "Click Here",
            "size": 36,
            "style": "bold",
            "name": "text1",
            "hOffset": 250,
            "vOffset": 100,
            "alignment": "center",
            "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
        }
    }
}

formatter = Formatter()
formatter.indent_spaces = 2
formatter.max_inline_complexity = 2 # Low complexity to demonstrate compactness
formatter.json_eol_style = EolStyle.LF
formatter.simple_bracket_padding = False # To make it more compact

formatted_json_string = formatter.serialize(data)
print(formatted_json_string)

# Example of customizing formatter options
another_formatter = Formatter()
another_formatter.use_tab_to_indent = True
another_formatter.max_total_line_length = 60
print('\n--- Formatted with tabs and shorter lines ---')
print(another_formatter.serialize(data))

view raw JSON →