繁体   English   中英

Python - 将元素添加到 json 文件

[英]Python - adding an element to a json file

在我的 python 程序中使用 json 文件。 我需要从函数中修改 json 文件以添加一个空的“占位符”元素。 我只想为 convID 对象中包含的键添加一个空元素。 json 库是否允许以更简单的方式将元素附加到 json 文件?

示例.json:

{"1005672": "Testing needles note", "1005339": "Reply", "988608": "Received the message"}

我希望这种情况发生( convID表示存储在 convID 对象中的密钥):

{"1005672": "Testing needles note", "1005339": "Reply", "988608": "Received the message", "*convID*": "none"}

我猜我将不得不将 json 加载到字典对象中,进行修改并将其写回文件......但这对我来说很难,因为我仍在学习。 这是我的挥杆:

def updateJSON():
   jsonCache={} # type: Dict

   with open(example.json) as j:
      jsonCache=json.load(j)

   *some code to make append element modification

    with open('example.json', 'w') as k:
       k.write(jsonCache)

请使用 PEP8 风格指南。

以下代码段将起作用

导入json

def update_json():
    with open('example.json', 'r') as file:
        json_cache = json.load(file)
        json_cache['convID'] = None
    with open('example.json', 'w') as file:
        json.dump(json_cache, file)

要向 dict 添加一个键,您只需为其命名:

your_dict['convID'] = 'convID_value'

因此,您的代码将类似于:

import json

# read a file, or get a string
your_json = '{"1005672": "Testing needles note", "1005339": "Reply", "988608": "Received the message"}'

your_dict = json.loads(your_json)

your_dict['convID'] = 'convID_value'

因此,将它与您的代码一起使用,它将是:

def update_json():
    json_cache = {}

    with open('example.json', 'r') as j:
        json_cache = json.load(j)

    json_cache['convID'] = 'the value you want'

    with open('example.json', 'w') as k:
        json.dump(json_cache, f)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM