shayan bahrainy
shayan bahrainy

Reputation: 63

Processing Dictionary inside JSON

I have some code:

import requests

headers = {
    'authority': 'business.upland.me',
    'appversion': '0.13.24',
    'authorization': '(My auth code here)',
    'platform': 'web',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36',
    'content-type': 'application/json',
    'accept': '*/*',
    'sec-gpc': '1',
    'origin': 'https://play.upland.me',
    'sec-fetch-site': 'same-site',
    'sec-fetch-mode': 'cors',
    'sec-fetch-dest': 'empty',
    'referer': 'https://play.upland.me/',
    'accept-language': 'en-US,en;q=0.9',
    'if-none-match': 'W/^\\^10d-dcHHdBCD0xcI+3PFMmJm3d3EMaQ^\\^',
}

response = requests.get('https://business.upland.me/contributions/5804', headers=headers)
stakersout = response.content
stakersout = list(stakersout)
print(stakersout)
#get dictionaries here
print(dictionary['username'])

That returns some JSON:

b'[{"id":"6078a1e0-9103-11eb-a53e-c9ee97fa6188","is_in_jail":false,"pending":false,"avatar_image":"https://upland-image.s3.amazonaws.com/avatars/exclusive/memo_day.svg","avatar_color":"#E900FD","price":0.46,"username":"cryptofan","created_at":"2021-06-25T02:10:35.825Z"}]'

In this case, their is one dictionary inside but usually their will be more. How would I get each dictionary and process it in a for loop?

Upvotes: 0

Views: 81

Answers (2)

Cfomodz
Cfomodz

Reputation: 516

First, we will take the response and turn it into a python object.

stakersout = response.json()

We are now left with a list of dictionaries. In this case, a list of length one.

[{"id":"6078a1e0-9103-11eb-a53e-c9ee97fa6188","is_in_jail":false,"pending":false,"avatar_image":"https://upland-image.s3.amazonaws.com/avatars/exclusive/memo_day.svg","avatar_color":"#E900FD","price":0.46,"username":"cryptofan","created_at":"2021-06-25T02:10:35.825Z"}]

Now we can address that object within a for loop as you would with any other list.

For user in stakersout:
    print("Username is: " + user["username"])
    #do whatever else you want

As shown in the for loop above, you can use a dictname["key"] notation to get the data from within the dictionary, just like a standard python dictionary - since it now is just a standard list of standard python dictionaries.

Upvotes: 1

buran
buran

Reputation: 14233

stakersout = response.json()
for my_dict in stakersout:
    # process my_dict
    print(my_dict)

Also note using response.json().

Upvotes: 1

Related Questions