简体   繁体   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?

Problem Summary: 问题摘要:

I am calling an API with requests.get. 我正在使用requests.get调用API。 The returned JSON object is being saved to a variable as a JSON dictionary: 返回的JSON对象将作为JSON字典保存到变量中:

data = json.loads(response.text)

I need to access that dictionary, then replace one of its keys' values, then I need to POST the new dictionary back to the API. 我需要访问该字典,然后替换其中一个键的值,然后我需要将新字典POST回API。 I tried this by creating a function. 我通过创建一个函数来尝试这个。 The value is originally 'False' and I need to change it to be 'True': 该值最初为“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)

The problem that arises is that I can't figure out how to update the JSON library without calling the original JSON library again. 出现的问题是我无法弄清楚如何在不再调用原始JSON库的情况下更新JSON库。 How do I do the usual request.get, then use my function to change the value I need to change, then POST it again to a new API call like requests.post? 我如何执行通常的request.get,然后使用我的函数来更改我需要更改的值,然后将其再次POST到一个新的API调用,如requests.post?

Your example doesn't replace the key, rather it creates a new entry with the value from the original key. 您的示例不替换密钥,而是使用原始密钥的值创建新条目。 If you need to simply update it then check if the key is in the dict, change it if it is, then return the new result. 如果您只需要更新它,那么检查密钥是否在dict中,如果是,则更改它,然后返回新结果。 Also, you don't need the json lib with requests. 此外,您不需要带有请求的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