如何用Python从Roblox presence API获取JSON数据并解决类型错误?
解决Roblox Presence API获取userPresenceType时的TypeError问题
你的代码出错是因为用json.dumps()把解析好的JSON对象转成了字符串,字符串只能用整数下标访问单个字符,自然没法用'userPresenceType'这种键名取值,这就是你看到TypeError: string indices must be integers, not 'str'的原因。
json.loads(response.text)已经把接口返回的文本转换成了Python可以直接操作的字典/列表对象,完全不需要再用json.dumps()转成字符串格式。另外还要注意Roblox这个接口的返回结构:userPresenceType是嵌套在userPresences数组的元素里的,需要先拿到这个数组再取对应字段。
修正后的代码如下:
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) # 直接从解析后的JSON对象中取值,userPresences是数组,取第一个元素的userPresenceType print(json_data['userPresences'][0]['userPresenceType']) print("Status Code", response.status_code)
几个关键要点:
- 删除
new_jsondata = json.dumps(json_data, indent=4)这一行,直接使用json_data这个Python对象 - 接口返回的
userPresences是数组类型(因为支持传入多个userIds),所以要用[0]取第一个用户的 presence 数据 - 如果需要打印格式化的JSON字符串用于调试,可以单独用
print(json.dumps(json_data, indent=4)),但不要把这个字符串当成数据对象来操作
内容的提问来源于stack exchange,提问作者user22030485
相关产品推荐
相关产品推荐

