簡體   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