Python 中的解析响应

Parsing response in Python

我无法解析我在 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)

This is the error I get

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 时在调试模式下看到的

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

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

它是一个字典列表,当你在列表中运行“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}