How to get line breaks of a JSON attribute using Python?

79 views Asked by At

JSON file :

{
    "items": [
        {
            "item1": "/xyz"
        },
        {
            "item2": "/yzx"
        },
        {
            "item3": "/zxy"
        }
    ]
}

Python Code :

def funct(request):
    input = ''

    # Request body
    data = maybe_str(request.data())
    if data:
        if is_json(request.headers.get('Content-Type', '')):
            input = json.dumps(data, indent=2, sort_keys=True,
                           separators=(',', ': '))
        else:
            input = data

    return input

The python function returns a formatted string and then places it within Sphinx CodeBlock.

Output :

{ "items": [ { "item1": "/xyz", "item2": "/yzx", "item3": "/zxy" }, { "item1": "/xyz", "item2": "/yzx", "item3": "/zxy" } ] }

Desired Output:

{
"items": [
    {
      "item1": "/xyz",
      "item2": "/yzx",
      "item3": "/zxy"
    },
    {
      "item1": "/xyz",
      "item2": "/yzx",
      "item3": "/zxy"
    }
  ]
}

I tried using .replace('\\n','\n') from this stackoverflow issue but still didnt work.

Edit: I have changed some variable names. I used "input" here just as an example

1

There are 1 answers

2
Dmitriy On
def funct(request):
    input = ''

    # Request body
    data = maybe_str(request.data())
    if data:
        if is_json(request.headers.get('Content-Type', '')):
            input = json.dumps(data, indent=2, sort_keys=True,
                       separators=(',', ': '))
        else:
            input = data

    return json.dumps(input, indent=4) # returns prettified json str

This solution works for me in a python3 shell. In case this does not help, you can try using simplejson, ujson, or json5, which all are also able to format JSON.

And also, you should not use input as a variable name, because it's a reserved word — try using json_input instead.