如何在 JSON 文件中已经存在的列表中导出字典? |蟒蛇

时间:2021-05-10 15:12:09

标签: python json python-3.x file

我想在我的数据数组中获取下面的字典,因为大多数教程都向您展示了如何将变量直接放入 json 中,而无需将其排序到数组或对象中。

JSON:

#JSON file

{
    "data" : 
    [
      
    
    ]

}


我想导出的python文件:

import json 

#Python file

your_facebook_info = {'name':'johhny', 'age':213, 'money':'lots'}


预期结果:

{
    "data" : 
    [
      your_facebook_info = {
       'name':'johhny', 
       'age':213, 
       'money':'lots'
      }
    
    ]

}

1 个答案:

答案 0 :(得分:2)

试试这个。您读取文件,追加新数据,将数据写回文件。

import json 

#Python file

your_facebook_info = {'name':'johhny', 'age':213, 'money':'lots'}
with open('text.json','r') as inputfile:
  data = json.load(inputfile)
  data['data'].append(your_facebook_info)

with open("text.json", "w") as outfile: 
    json.dump(data, outfile)
相关问题