python - 如何在循环python中编写具有多个字典的.json文件
问题描述
while True:
my_dict={}
b = box.tolist()
t = np.array(timestamp).tolist()
my_dict["coordinates"] = b
my_dict["timestamp"]= t
all_dict.append(my_dict)
for my_dict in all_dict:
with open("co.json", 'a') as fp:
json.dump(my_dict,fp)
输出需要为json格式,但不是这样{ {},{},{} }
,它只是转储为{}{}{}
不带逗号分隔符且不带外层{}
解决方案
那是因为您正在转储每个子目录,就好像它是单独的单个字典一样。所以它不写包装大括号或逗号。
相反,不要循环子字典,只需转储整个字典列表(indent
如果需要,添加参数允许“漂亮打印”转储):
with open("co.json", 'w') as fp:
json.dump(all_dict,fp,indent=2)
(您现在也不需要追加模式,只需打开以进行写入/截断)请注意,您不会得到 dicts 的“dict”,而是得到一个 dicts列表:like [ {a:b}, {c:d} ]
,这也是有效的 json。
推荐阅读
- azure - 在 Azure 上设置 Jenkins、Docker、Kubernetes ci/cd
- javascript - 在javascript中比较两个相同的字符串失败
- sql - 查询将比递归 cte 执行得更好
- php - 在变量中添加 wp_insert_post() 重要吗?
- react-native - React Native fetch 在发布 multipart/form-data 时抛出错误
- jquery - 单击与 div 的内部按钮冲突的 slideToggle div
- php - 生成保存激活密钥作为产品密钥
- css - 防止自动隐藏地址栏
- r - 在 R 中重塑复杂的数据集
- android - 将 RecyclerViews itemAnimator 设置为 null 不会删除动画