![](/img/trans.png)
[英]How to create a JSON file from several dictionaries and one list in python
[英]How to create newline delimited json-lines file from list of python dictionaries
我正在尝试创建一个 JSON 行的数据文件,以便与 google cloud AI 平台对在线预测的要求兼容。
现在我有每个数据点的字典列表。 它看起来像这样:
data = [{'values': [0,1,0], 'key': 0}, {'values': [1,1,0], 'key': 1}]
我使用以下代码将此数据导出到data.json :
import json
json_filepath = "data.json"
with open(json_filepath, 'w') as f:
json.dump(data, f)
问题是,这个data.json文件看起来就像我的数据(即字典列表)。 如何使这个data.json文件成为列表中每个字典的换行分隔集合? 换句话说,我怎样才能让它看起来像这样:
{'values': [0,1,0], 'key': 0}
{'values': [1,1,0], 'key': 1}
您可以遍历数组并转储每个对象,后跟一个新行'\\n'
:
with open(json_filepath, 'w') as f:
for d in data:
json.dump(d, f)
f.write('\n')
或者,您可以使用json.dumps
、 str.join
和map
使用json.dumps
:
with open(json_filepath, 'w') as f:
f.write('\n'.join(map(json.dumps, data)))
with open(json_filepath, "w") as f:
for datum in data:
f.write(json.dumps(datum))
f.write("\n")
我还应该提到一般这被称为“JSON 行”数据格式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.