[Python] How to implement custom indentation when pretty-printing with the JSON module?

Discussão em 'Python' iniciado por Stack, Agosto 28, 2025.

  1. Stack

    Stack Membro Participativo

    So I'm using Python 2.7, using the json module to encode the following data structure:

    'layer1': {
    'layer2': {
    'layer3_1': [ long_list_of_stuff ],
    'layer3_2': 'string'
    }
    }


    My problem is that I'm printing everything out using pretty printing, as follows:

    json.dumps(data_structure, indent=2)


    Which is great, except I want to indent it all, except for the content in "layer3_1" — It's a massive dictionary listing coordinates, and as such, having a single value set on each one makes pretty printing create a file with thousands of lines, with an example as follows:

    {
    "layer1": {
    "layer2": {
    "layer3_1": [
    {
    "x": 1,
    "y": 7
    },
    {
    "x": 0,
    "y": 4
    },
    {
    "x": 5,
    "y": 3
    },
    {
    "x": 6,
    "y": 9
    }
    ],
    "layer3_2": "string"
    }
    }
    }


    What I really want is something similar to the following:

    {
    "layer1": {
    "layer2": {
    "layer3_1": [{"x":1,"y":7},{"x":0,"y":4},{"x":5,"y":3},{"x":6,"y":9}],
    "layer3_2": "string"
    }
    }
    }


    I hear it's possible to extend the json module: Is it possible to set it to only turn off indenting when inside the "layer3_1" object? If so, would somebody please tell me how?

    Continue reading...

Compartilhe esta Página