简体   繁体   English

如何以JSON格式从post响应中访问数据

[英]How to access data from a post response in JSON format

I am trying to access a dictionary that has been returned after making a post to an API, but I am having difficulty formatting the data with JSON. 我正在尝试访问在发布API后返回的字典,但我在使用JSON格式化数据时遇到了困难。

It seems to be returning the data as a dictionary but I receive the error 'list indices must be integers or slices, not str' which makes me believe that it is just returning a list that looks like a dictionary. 它似乎将数据作为字典返回,但我收到错误'列表索引必须是整数或切片,而不是str',这使我相信它只是返回一个看起来像字典的列表。 I have tried using json.loads() and trying to access the data through lists but I can't seem to get it. 我已经尝试使用json.loads()并尝试通过列表访问数据,但我似乎无法得到它。 The data I am trying to has multiple sub dictionaries/lists. 我试图的数据有多个子词典/列表。

resp = post(url = endpoint_url, data = data, headers = headers)
data_for_process = resp.json()
print(data_for_process['pages']['keyValuePairs']['key'])

I expected the print statement to return the value for that specific key but I get the error instead. 我希望print语句返回该特定键的值,但我得到了错误。

Any help much appreciated. 任何帮助非常感谢。

you can use the json library of python 你可以使用python的json库

import json
import pprint

resp = post(url = endpoint_url, data = data, headers = headers)
resp_json = json.loads(resp.content)
pprint.pprint(resp_json) # to display the dict prettier

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

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