簡體   English   中英

在使用requests.get調用API后,如何從返回的JSON對象替換鍵的值?

[英]How do I replace a value of a key from a returned JSON object after calling an API using requests.get?

問題摘要:

我正在使用requests.get調用API。 返回的JSON對象將作為JSON字典保存到變量中:

data = json.loads(response.text)

我需要訪問該字典,然后替換其中一個鍵的值,然后我需要將新字典POST回API。 我通過創建一個函數來嘗試這個。 該值最初為“False”,我需要將其更改為“True”:

def updatedata(data):
    k = 'my_key'
    for k, v in data.items():
        if k == 'my_key':
            data[v] = 'True'

response = requests.get(my_URL, headers=my_headers)
data = json.loads(response.text)
updatedata(data)

newlibary = updatedata()
print(newlibrary)

出現的問題是我無法弄清楚如何在不再調用原始JSON庫的情況下更新JSON庫。 我如何執行通常的request.get,然后使用我的函數來更改我需要更改的值,然后將其再次POST到一個新的API調用,如requests.post?

您的示例不替換密鑰,而是使用原始密鑰的值創建新條目。 如果您只需要更新它,那么檢查密鑰是否在dict中,如果是,則更改它,然后返回新結果。 此外,您不需要帶有請求的json lib。

import requests

def updatedata(data, key, new_value):
    if key in data:
        data[key] = new_value
    return data

response = requests.get(my_URL, headers=my_headers)
data = response.json()
response = requests.post(myUrl, json=updatedata(data, 'my_key', True))
>>> myDict = {"testing": 1, "testing2": 2, "my_key": 3} >>> >>> >>> def updatedata(data): ... k = 'my_key' ... for key, val in data.items(): # use a different variable to reduce confusion ... if key == 'my_key': ... data[key] = 'True' # specify the key, not the value ... return data # optional, unless you want to save into a new variable ... >>> >>> updatedata(myDict) >>> myDict {'testing': 1, 'testing2': 2, 'my_key': 'True'} >>>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM