Python和JSON.dump:如何将内部数组放在一行中

21

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

如何将内部数组变成一行?谢谢


1
不要使用 indent=4。当然,这会将整个内容放在一行上。如果你也不想这样,你就必须编写自己的转储程序。 - John Gordon
1个回答

13

我认为如果输出格式发生变化,这可能会出现错误,但这只是一个想法?

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接