gpt4 book ai didi

python 和json.dump : how to make inner array in one line

转载 作者:行者123 更新时间:2023-12-01 01:46:21 24 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





How to implement custom indentation when pretty-printing with the JSON module?

(10 个回答)


3年前关闭。




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

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

关于 python 和json.dump : how to make inner array in one line,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48969984/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com