【问题标题】:Parsing response in Python在 Python 中解析响应
【发布时间】:2020-08-09 21:40:40
【问题描述】:

我无法解析我在 python 中的响应,感谢任何关于我需要更改的反馈!

url = 'https://someURL'
headers = {'Authorization' : 'Bearer <MyToken>'}

r = requests.get(url, headers=headers)

#This part prints entire response content in a text like format [{'x':'' ,'y':'', ...etc},{'x':'' ,'y':'', ...etc},...etc]

jsonResponse = r.json()
print("Entire JSON response")
print(jsonResponse)

# when I try to parse into each item and get the key value, I get an error
print("Print each key-value pair from JSON response")
for key, value in jsonResponse.items():
    print(key, ":", value)

这是我得到的错误

Traceback (most recent call last):
  File "blueiInitialSync.py", line 131, in <module>
    for key, value in jsonResponse.items():
AttributeError: 'list' object has no attribute 'items'
bash: parse_git_branch: command not found

这也是我在调试模式下看到的r

【问题讨论】:

  • jsonResponse 的类型为 list。试试for key, value in jsonResponse[0].items():

标签: python httprequest httpresponse


【解决方案1】:

您正在遍历一个字典列表,而不仅仅是一个字典。您需要解压列表中的每个字典。

for d in jsonResponse:
    for key, value in d.items():
        print(key, ":", value)

【讨论】:

  • 谢谢!那行得通!我有一个后续问题,在上面的代码中,我对我通过邮递员调用获得的不记名令牌进行了硬编码......我不确定如何在 python 中执行实际的发布请求,我已经在 javascript 中完成了,就像这样` `` var options = {方法:'POST',url:'myurl',qs:{grant_type:'client_credentials',client_id:'xyz',client_secret:'abc'},标头:{'cache-control':'否-cache'}};``` 但我在 python 中做同样的事情时遇到了麻烦。
  • @CatGirl19 这似乎是另一个问题主题。为此发布另一个问题。
【解决方案2】:

它是一个字典列表,当您在列表上运行“for”时,它会为每个字典运行一次。单独打印字典,例如;

list_of_dict = [{"a": 5, "b": 10},{"c": 15, "d": 20}]
for i in list_of_dict:
    print(i)

会打印出来,

{'a': 5, 'b': 10}

{'c': 15, 'd': 20}

【讨论】:

    猜你喜欢
    • 2011-05-26
    • 2014-05-27
    • 1970-01-01
    • 1970-01-01
    • 2016-05-05
    • 1970-01-01
    • 2022-06-11
    • 2021-10-29
    • 1970-01-01
    相关资源
    最近更新 更多