蟒蛇& json.dump:如何在一行中创建内部数组

时间:2018-02-25 03:37:55

标签: python json

我的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 个答案:

答案 0 :(得分:2)

我认为如果输出的格式发生了变化,但这只是一个想法,这可能容易出错?

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

或多次替换(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"]
    }
]