Skip to content Skip to sidebar Skip to footer

In Json Output, Force Every Opening Curly Brace To Appear In A New Separate Line

With json.dumps(some_dict,indent=4,sort_keys=True) in my code: I get something like this: { 'a': { 'x':1, 'y':2 }, 'b': { 'z':3, 'w':4

Solution 1:

You can use a regular expression replacement on the result.

better_json = re.sub(r'^((\s*)".*?":)\s*([\[{])', r'\1\n\2\3', json, flags=re.MULTILINE)

The first capture group matches everything up to the : after the property name, the second capture group matches the whitespace before the property name, and the third capture group captures the { or [ before the object or array. The whitespace is then copied after the newline, so that the indentation will match properly.

DEMO

Solution 2:

Building on Barmar's excellent answer, here's a more complete demo showing how you can convert and customize your JSON in Python:

import json
import re


# JSONifies dict and saves it to filedefsave(data, filename):

    withopen(filename, "w") as write_file:

        write_file.write(jsonify(data))


# Converts Python dict to a JSON string. Indents with tabs and puts opening# braces on their own line.defjsonify(data):

    default_json = json.dumps(data, indent = '\t')

    better_json = re.sub(
        r'^((\s*)".*?":)\s*([\[{])',
        r'\1\n\2\3',
        default_json,
        flags=re.MULTILINE
    )

    return better_json


# Sample data for demo
data = {
    "president":
    {
        "name": "Zaphod Beeblebrox",
        "species": "Betelgeusian"
    }
}

filename = 'test.json'# Demoprint("Here's your pretty JSON:")
print(jsonify(data))
print()
print('Saving to file:', filename)
save(data, filename)

Post a Comment for "In Json Output, Force Every Opening Curly Brace To Appear In A New Separate Line"