【问题标题】:How can I export a dictionary inside a list that's already in a JSON file? | Python如何在 JSON 文件中已经存在的列表中导出字典? | Python
【发布时间】:2021-08-01 00:15:27
【问题描述】:

我想在我的数据数组中获取下面的字典,因为大多数教程都向您展示了如何将变量直接放入 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'
      }
    
    ]

}

【问题讨论】:

  • 你已经在做import json了。你查看json.load()json.dump() 了吗?
  • 是的,但这只是将它们转储,当它们被转储时,我需要将它们放入列表中

标签: python json python-3.x file


【解决方案1】:

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

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)

【讨论】:

    猜你喜欢
    • 2011-04-23
    • 2022-06-23
    • 1970-01-01
    • 1970-01-01
    • 2018-02-07
    • 2018-05-28
    • 2023-01-20
    • 2018-12-20
    • 2021-08-19
    相关资源
    最近更新 更多