简体   繁体   中英

Parsing response in Python

Im having trouble parsing through my response in python, any feedback on what I need to change is appreciated!

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

Also this is what I see in debug mode when drilling into r在此处输入图像描述

You're looping over a list of dicts not just a dict. You need to unpack each dict in the list.

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

It is a list of dictionaries, when you run "for" on the list it runs once for every dictionary. To print the dictionaries individually, example;

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

Will print out,

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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