21

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

BAE
  • 8,550
  • 22
  • 88
  • 171
  • 1
    Don't use `indent=4`. Of course that will put the entire thing on one line. If you don't want that either, you'll have to write your own dump routine. – John Gordon Feb 25 '18 at 03:44

1 Answers1

13

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"]
    }
]
G_M
  • 3,342
  • 1
  • 9
  • 23