Python 在JSON文件中再添加一个属性

Python 在JSON文件中再添加一个属性,python,json,random,Python,Json,Random,因此,我有一个生成的JSON,它看起来像(有很多JSON只是具有唯一的ID) 我试图“附加”一个新字段,但我得到一个错误 with open('data.json', 'w') as file: json.dump(write_list, file) file.close() with open('data.json', 'w') as json_file: entry = {'parentId': random.randrange(0, 487, 2)} json_f

因此,我有一个生成的JSON,它看起来像(有很多JSON只是具有唯一的ID)

我试图“附加”一个新字段,但我得到一个错误

with open('data.json', 'w') as file:
    json.dump(write_list, file)
file.close()

with open('data.json', 'w') as json_file:
    entry = {'parentId': random.randrange(0, 487, 2)}
    json_file.append(entry, json_file)
json_file.close()

生成后,是否有办法再向其添加一个“键:值”?

执行所需操作的步骤为文件:

  • 将整个JSON文件解析到python字典中
  • 将条目添加到字典中
  • 将字符串序列化回JSON
  • 将JSON文件写回该文件
  • 有两个问题:

  • 您正在使用
    json.dump
    生成列表,但没有使用
    json.load
    重新创建Python数据结构
  • 在第二次打开调用中,您将使用
    w
    模式打开文件,这将截断文件
  • 尝试将每一步分解为自己的步骤,并将变异的数据和写入磁盘的数据分开

    with open('data.json', 'w') as file:
        json.dump(write_list, file)
    #file.close()                     # manually closing files is unnecessary, 
                                      # when using context managers
    
    with open('data.json', 'r') as json_file:
        write_list = json.load(json_file)
        entry = {'parentId': random.randrange(0, 487, 2)}
        write_list.append(entry)
    
    with open('data.json', 'w') as json_file:
        json.dump(write_list, file)
    

    在我使用Tim McNamara advice完成了这个特性之后,我找到了一种更漂亮的方法,可以向文件中的每个JSON dict添加新行

    for randomID in write_list:
        randomID['parentId'] = random.randrange(0, 487, 2)
    
    with open('data.json', 'w') as file:
        json.dump(write_list, file)
    

    请在此处粘贴3-5行JSON文件。不清楚结构是什么(JSON或JSON行)。{“id”:3,“name”:“name”,“dep”:“dep”,“Title”:“Title”,“email”:“email”},{“id”:4,“name”:“name”,“dep”:“dep”:“dep”,“Title”:“Title”,“email”:“email”},{“id”:5,“name”:“name”,“dep”:“dep”,“Title”:“Title”,“email”:“email”}@上面添加了coldspeed,我想让它们看起来像{“id”:3,“name”:“name”,“dep”:“dep”,“Title”:“Title”,“email”:“email”,“parentId”:“2”}有什么错误吗?是的,可能就是这样,有很多错误
    for randomID in write_list:
        randomID['parentId'] = random.randrange(0, 487, 2)
    
    with open('data.json', 'w') as file:
        json.dump(write_list, file)