Python无法访问字典 [英] Python Can't access dictionary
问题描述
在尝试使用python访问字典时获取TypeError: string indices must be integers
.我试过使用json.loads(r2)
产生了"TypeError: the JSON object must be str, bytes or bytearray, not dict"
Getting TypeError: string indices must be integers
when trying to access a dictionary in python. I've tried using json.loads(r2)
thos produces "TypeError: the JSON object must be str, bytes or bytearray, not dict"
即使不确定Im是否在正确的轨道上,我所需要做的就是将看起来像一个长字符串的JSON转换为x['SomeKey']
之类的东西,并使用iteritems()
或类似方式将这些键处的值显示出来?
Not even sure if Im on the right track here, all I need to do is get the JSON which appears to be in one long string into something like x['SomeKey']
and the value at those keys using iteritems()
or similar?
r = requests.get(url, headers=headers)
r2 = r.json()
seq = json.dumps(r2)
print(seq['remotecontrol_id'])
推荐答案
r.json()
已经返回了字典,所以我不确定为什么将r2
传递给json.dumps
并返回字符串(因此s
).您收到的错误消息甚至表明("TypeError:JSON对象必须是str,字节或字节数组,而不是 dict ")
r.json()
already returns a dictionary so I'm not sure why you pass r2
to json.dumps
that returns a string (hence the s
). The error message you received even suggests that ("TypeError: the JSON object must be str, bytes or bytearray, not dict")
您的代码应为
r = requests.get(url, headers=headers)
r2 = r.json()
print(r2['remotecontrol_id'])
这篇关于Python无法访问字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!