使用Python附加到Json对象

问题描述

我想附加到此json对象。 追加前的JSON:

{
  "Profiles": [
  ]
}

我要添加此信息:

    {
      "Profile": "1","First": "1","Last": "1","Credit Card": "","Exp Month": "1","Exp Year": "1","Cvv Code": "1","Home Address": "1","Zip Code": "1","State": "1"
    }

我尝试这样做:

            #Profile Data
            data['Profiles'].append({
                'Profile': profile_name,'First': first,'Last': last,'Credit Card': cc,'Exp Month': exp_month,'Exp Year': exp_year,'Cvv Code': cvv,'Home Address': addr,'Zip Code': zip_code,'State': state
            })

它不仅重复添加该信息,还会重复json文件中已有的内容,然后在其外部添加信息。 这是上面的结果:

{
  "Profiles": [
  ]
}{
  "Profiles": [
    {
      "Profile": "1","Credit Card": "1","Cvv Code": "","State": "1"
    }
  ]
}

基本上,我要完成的工作是向json对象(配置文件添加一堆配置文件

解决方法

我认为您应该首先使用此功能在python中加载json数据:

import json
data = json.load(json_file) 

然后可以使用append方法。之后,您可以使用json.dumps()函数将其转换回json字符串。

此处提供更多信息:https://www.geeksforgeeks.org/append-to-json-file-using-python/