如何在循环python中使用多个字典编写.json文件

时间:2018-05-26 15:28:58

标签: python json python-3.6

 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格式,但它不像{ {},{},{} }那样,它只是转储为{}{}{}而没有逗号分隔符且没有外部{}

2 个答案:

答案 0 :(得分:2)

这是因为您将每个子目录转储为单独的单个词典。所以它不会写包裹括号或逗号。

相反,不要在子语句上循环,只需转储整个dicts列表(添加indent参数允许" prettyprint"如果需要转储):

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

(你现在不需要追加模式,只需打开写入/截断) 请注意,您没有获得" dict"结果是dicts而是一个 list 的结果:像[ {a:b}, {c:d} ],这也是有效的json。

答案 1 :(得分:0)

with open("coordinates.json", 'w') as fp: 
    fp.write('{')
    for my_dict in all_dict:
        if (my_dict!=all_dict[-1]):
            #fp.write('"key":'+json.dumps(my_dict)+',\n')
        else:
            fp.write('"key":'+json.dumps(my_dict)) 
    fp.write('}')