x = { "people": [{ "owner": "bob", "petname": "fido", "species": "dog", "size": "chunky"}, {"owner": "mary","petname": "marvin","species": "cat","size": "cat"}]}
y = json.dumps(x)
z = json.loads(y)
for i in z:
if i["owner"] == "bob":
print(i['petname'])
break
该代码的目标是通过为所有者命名为“ bob”来返回“ fido”
但是我得到的只是TypeError:字符串索引必须是整数。我究竟做错了什么?谢谢
You are iterating the base dictionary instead of iteration list under
people
Iterate over
z["people"]
which contains alist
, instead of iteratingz
Solution
码:
If you need
JSON
:输出:
当你做
每个密钥都被获取,即,i ='people'。所以当你这样做
产生错误,因为我是一个字符串。 因此使用: