[英]How to write a list to a JSON file without losing the comma
I'm trying to develop code in Python that formats a list in a JSON file without removing the commas or brackets. 我正在尝试使用Python开发代码,该代码在不删除逗号或方括号的情况下格式化JSON文件中的列表。 The list is supposed to have each set of data on a new line.
该列表应该在每行上都有每组数据。 I'm able to handle the brackets on my own, but I'm having issues with the commas.
我可以自己处理括号,但是逗号有问题。
I've already tried include a indent statement in .dump, but it's not the correct format. 我已经尝试过在.dump中包含一个缩进语句,但这不是正确的格式。
#Attempt 1
for data in data:
outfile.write('\t')
json.dump(data, outfile)
outfile.write('\n')
#Attempt 2
for obj in data:
outfile.write('\t' + json.dumps(obj) + '\n')
Expected output 预期产量
[
[1, 12],
[2, 7],
[3, 6]
]
Actual output 实际产量
[
[1, 12]
[2, 7]
[3, 6]
]
Why are you iterating at all? 你为什么要迭代呢? You should just dump the whole list in one go:
您应该一次性丢弃整个列表:
outfile.write(json.dumps(data))
You could modify your Attempt 2
to add the comma to each outputted item except the last: 您可以修改“
Attempt 2
以将逗号添加到每个输出项(最后一项除外):
for ndx, obj in enumerate(data, 1):
outfile.write(
'\t'
+ json.dumps(obj)
+ (',' if ndx != len(data) else '')
+ '\n'
)
I would use something like: 我会用类似的东西:
# Python 3+
import json
objects = [[1, 2], [3, 4]]
# the magic happens next line:
dump = "[\n" + ",\n".join([ "\t" + json.dumps(obj) for obj in objects ]) + "\n]"
print(dump)
with open("out", "w") as outfile:
outfile.write(dump)
json.dumps(obj)
outputs JSON representation of the object as string. json.dumps(obj)
以字符串形式输出对象的JSON表示形式。 A tab character is appended to each object representation and they are joined using ,\\n
. 制表符会附加到每个对象表示形式,并使用
,\\n
。
Output: 输出:
[
[1, 2],
[3, 4]
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.