【问题标题】:Appending To A Json Object Using Python [closed]使用 Python 附加到 Json 对象 [关闭]
【发布时间】:2020-10-25 21:01:12
【问题描述】:

我想附加到这个 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",
      "First": "1",
      "Last": "1",
      "Credit Card": "1",
      "Exp Month": "1",
      "Exp Year": "1",
      "Cvv Code": "",
      "Home Address": "1",
      "Zip Code": "1",
      "State": "1"
    }
  ]
}

基本上我想要完成的是将一大堆配置文件添加到 json 对象(配置文件)。

【问题讨论】:

  • 我不知道你是怎么实现的,比如用python脚本输出,真的很难不小心。
  • @OlvinR​​oght 难道是因为我打开文件的模式是读/写'r+'?
  • 啊,是的,这就是原因。您应该重写文件而不是附加,使用'w+'
  • @OlvinR​​oght 所以其他一切都保持不变只是改变模式?
  • 试试吧,如果它有帮助 - 太棒了。

标签: python json object


【解决方案1】:

我认为你应该首先使用这个函数在 python 中加载你的 json 数据:

import json
data = json.load(json_file) 

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

更多信息在这里:https://www.geeksforgeeks.org/append-to-json-file-using-python/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-12
    • 2021-09-26
    • 1970-01-01
    • 2017-11-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多