python & json.dump:如何在一行中制作内部数组



我的python代码:

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

输出文件是

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

如何使内部数组成一条线?谢谢

我认为,如果输出的格式更改,但只是一个想法,这可能是错误的吗?

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

或多个替代品(这样会更好(:

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

最新更新