Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python & json.dump: how to make inner array in one line [duplicate]

Tags:

python

json

My python codes:

with open('outputFile.json', 'w') as outfile:
    json.dump(ans, outfile, indent=4, separators=(',', ': '))

The output file is

[
    {
        "rowLength": 5,
        "alphabet": [
            "Q",
            "W",
            "I",
            "B",
            "P",
            "A",
            "S"
        ]
    },
    {
        "rowLength": 3,
        "alphabet": [
            "S",
            "D",
            "E",
            "U",
            "I",
            "O",
            "L"
        ]
    }
]

How to make the inner array into one line? Thanks

like image 995
BAE Avatar asked Feb 25 '18 03:02

BAE


1 Answers

I think this could be error-prone if the format of the output ever changed but just as an idea?

>>> d = [{'rowLength': 5, 'alphabet': ['Q', 'W', 'I', 'B', 'P', 'A', 'S']}, {'rowLength': 3, 'alphabet': ['S', 'D', 'E', 'U', 'I', 'O', 'L']}]
>>> import json
>>> output = json.dumps(d, indent=4)
>>> import re
>>> print(re.sub(r'",\s+', '", ', output))
[
    {
        "rowLength": 5,
        "alphabet": [
            "Q", "W", "I", "B", "P", "A", "S"
        ]
    },
    {
        "rowLength": 3,
        "alphabet": [
            "S", "D", "E", "U", "I", "O", "L"
        ]
    }
]

Or with multiple replaces (something like this would be better):

>>> output = json.dumps(d, indent=4)
>>> output2 = re.sub(r'": \[\s+', '": [', output)
>>> output3 = re.sub(r'",\s+', '", ', output2)
>>> output4 = re.sub(r'"\s+\]', '"]', output3)
>>> print(output4)
[
    {
        "rowLength": 5,
        "alphabet": ["Q", "W", "I", "B", "P", "A", "S"]
    },
    {
        "rowLength": 3,
        "alphabet": ["S", "D", "E", "U", "I", "O", "L"]
    }
]
like image 99
G_M Avatar answered Oct 20 '22 12:10

G_M