Python Can't access dictionary

2020-05-10 18:18发布

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"

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'])

标签: python json
3条回答
Emotional °昔
2楼-- · 2020-05-10 18:48

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")

Your code should be

r = requests.get(url, headers=headers)
r2 = r.json()
print(r2['remotecontrol_id'])
查看更多
迷人小祖宗
3楼-- · 2020-05-10 18:51

Ok, I got it figured out, sort of...

for i in r2:

print(r2['stuff'][0]['someval1']) print(r2['stuff'][1]['asomeval2'])

Anyway, hits works

Thanks for all the great advice!

查看更多
Juvenile、少年°
4楼-- · 2020-05-10 19:11

The problem is that method dumps converts a python's dictionary into a string, therefore in the line seq['remote...'] you are accessing a string. You should access the variable r2 instead of seq

查看更多
登录 后发表回答