Search code examples
pythonroblox

How do I get the json data from a python request?


I want to get the "userPresenceType" value from presence.roblox.com api, but I get the error "TypeError: string indices must be integers, not 'str'"

I was able to get the data using print(new_jsondata[67]), but I don't think it is very practical.

Here is my code:

import requests
import json

url = "https://presence.roblox.com/v1/presence/users"
 
data = {
    "userIds": [
        1885004527
    ]
}
 
response = requests.post(url, json=data)
json_data = json.loads(response.text)
new_jsondata = json.dumps(json_data, indent=4)
print(new_jsondata['userPresenceType'])
print("Status Code", response.status_code)

Solution

  • When wanting to obtain json data from a requests method, you can use the response.json() method to have the returned json string converted to a python object for you.

    Then you can index into the python object:

    import requests
    
    url = "https://presence.roblox.com/v1/presence/users"
     
    data = {
        "userIds": [
            1885004527
        ]
    }
     
    response = requests.post(url, json=data)
    #print("Status Code", response.status_code)
    json_data = response.json()
    
    print(json_data['userPresences'][0]['userPresenceType'])
    

    Output: 2

    (ymmv)