0

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 enter image description here

1
  • jsonResponse is of type list. Try for key, value in jsonResponse[0].items(): Commented Aug 9, 2020 at 21:42

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! that worked! I have a follow up question, in the above code Im hardcoding my bearer token that I'm getting by doing a postman call...Im not sure how to do the actual post request in python, Ive done it in javascript like so ``` var options = {method: 'POST',url: 'myurl',qs:{grant_type: 'client_credentials', client_id: 'xyz',client_secret: 'abc'}, headers: {'cache-control': 'no-cache'}};``` but Im having trouble with doing the same in python.
@CatGirl19 This seems like another question topic. Post another question for this.
0

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}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.