【问题标题】:How to delete an element in a json file python如何删除json文件python中的元素
【发布时间】:2022-08-22 16:49:36
【问题描述】:

我正在尝试删除 json 文件中的元素,

这是我的 json 文件:

前:

{
    \"names\": [
        {
            \"PrevStreak\": false,
            \"Streak\": 0,
            \"name\": \"Brody B#3719\",
            \"points\": 0
        },
        {
            \"PrevStreak\": false,
            \"Streak\": 0,
            \"name\": \"XY_MAGIC#1111\",
            \"points\": 0
        }
    ]
}

运行脚本后:


{
    \"names\": [
        {
            \"PrevStreak\": false,
            \"Streak\": 0,
            \"name\": \"Brody B#3719\",
            \"points\": 0
        }
    ]
}

我将如何在 python 中做到这一点?该文件存储在本地,我正在决定通过每个元素中的名称删除哪个元素

谢谢

  • 您如何决定要删除哪个元素?
  • 按每个元素中的名称
  • 您已添加 python 标记,但您没有为您的问题添加任何代码。

标签: python json


【解决方案1】:

我会加载文件,删除项目,然后再次保存。例子:

import json
with open("filename.json") as f:
    data = json.load(f)
f.pop(data["names"][1]) # or iterate through entries to find matching name
with open("filename.json", "w") as f:
    json.dump(data, f)

【讨论】:

  • 读取文件应使用:data = json.load(f),写入应使用json.dump(data,f)。我确信f.write(data) 会导致错误。
【解决方案2】:

您必须读取文件,将其转换为 python 原生数据类型(例如字典),然后删除元素并保存文件。在你的情况下,这样的事情可能会起作用:

import json

filepath = 'data.json'
with open(filepath, 'r') as fp:
    data = json.load(fp)
del data['names'][1]

with open(filepath, 'w') as fp:
    json.dump(data, fp)

【讨论】:

    【解决方案3】:

    尝试这个:

    # importing the module
    import ast
      
    # reading the data from the file
    with open('dictionary.txt') as f:
        data = f.read()
      
    print("Data type before reconstruction : ", type(data))
          
    # reconstructing the data as a dictionary
    a_dict = ast.literal_eval(data)
    
    {"names":[a for a in a_dict["names"] if a.get("name") !="XY_MAGIC#1111"]}
    

    【讨论】:

      【解决方案4】:
      import json
      with open("test.json",'r') as f:
         data = json.loads(f.read())
         names=data.get('names')
         for idx,name in enumerate(names):
            if name['name']=='XY_MAGIC#1111':
               del names[idx]
               break
         print(names)
      

      为了读取文件,最好的方法是使用 with 语句,之后您可以使用 pythons json 库并将 json 字符串转换为 python dict。获得 dict 后,您可以访问这些值并根据需要进行操作。您可以使用 json.dumps() 将其转换为 json 然后保存

      【讨论】:

      • 您的代码当前有错误。读取文件应使用:data = json.load(f)
      • @quamrana 如果我们直接传递文件,那么我们可以使用 json.load 但我将字符串传递给 json.loads 而不是文件。加载接受字符串并加载接受文件
      • 那么,当您可以将文件传递给load(f) 时,为什么还要将字符串传递给loads()
      • 你是对的。但我有使用负载的习惯,因为大部分时间我都在处理字符串。
      • 是的,这很公平。 (我也是)
      【解决方案5】:

      这使用 python json 模块做正确的事情,然后将 json 漂亮地打印回文件:

      import json
      
      jsonpath = '/path/to/json/file.json'
      
      with open(jsonpath) as file:
          j = json.loads(file.read())
      
      names_to_remove = ['XY_MAGIC#1111']
      
      for element in j['names']:
          if element['name'] in names_to_remove:
              j['names'].remove(element)
              
      with open(jsonpath, 'w') as file:
          file.write(json.dumps(j, indent=4))
      

      【讨论】:

        猜你喜欢
        • 2021-03-15
        • 1970-01-01
        • 1970-01-01
        • 2020-09-18
        • 1970-01-01
        • 2022-08-11
        • 1970-01-01
        • 2021-01-11
        • 2021-08-02
        相关资源
        最近更新 更多