首页 > 解决方案 > 如何在循环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格式,但不是这样{ {},{},{} },它只是转储为{}{}{}不带逗号分隔符且不带外层{}

标签: pythonjsonpython-3.6

解决方案


那是因为您正在转储每个子目录,就好像它是单独的单个字典一样。所以它不写包装大括号或逗号。

相反,不要循环子字典,只需转储整个字典列表(indent如果需要,添加参数允许“漂亮打印”转储):

with open("co.json", 'w') as fp:  
    json.dump(all_dict,fp,indent=2)

(您现在也不需要追加模式,只需打开以进行写入/截断)请注意,您不会得到 dicts 的“dict”,而是得到一个 dicts列表:like [ {a:b}, {c:d} ],这也是有效的 json。


推荐阅读