Skip to content
Advertisement

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
    }
}

But I want something like this:

{
    "a":
    {
        "x":1,
        "y":2
    },
    "b":
    {
        "z":3,
        "w":4
    }
}

How can I force each opening curly brace to appear at the beginning of a new separate line?

Do I have to write my own JSON serializer, or is there a special argument that I can use when calling json.dumps?

Advertisement

Answer

You can use a regular expression replacement on the result.

better_json = re.sub(r'^((s*)".*?":)s*([[{])', r'1n23', 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

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement