我在使用下面的JSON和读取数据时遇到了一些问题,在查看了其他一些问题之后,似乎没有找到解决方案,除非我遗漏了一些东西。。在
感谢帮助:)
JSON:
{"ships":{"2":{"name":"Asp","alive":true,"id":2},"3":{"starsystem":{"systemaddress":"670417429889","id":"670417429889","name":"Diaguandri"},"station":{"id":3223343616,"name":"Ray Gateway"},"name":"SideWinder","alive":true,"id":3},"12":{"starsystem":{"systemaddress":"18263140541865","id":"73228","name":"Barnard's Star"},"station":{"id":128147960,"name":"Miller Depot"},"name":"Viper_MkIV","alive":true,"id":12},"13":{"starsystem":{"systemaddress":"673101653409","id":"673101653409","name":"Brestla"},"station":{"id":3224813312,"name":"Roed Odegaard Port"},"name":"Type7","alive":true,"id":13},"14":{"starsystem":{"systemaddress":"673101653409","id":"673101653409","name":"Brestla"},"station":{"id":3224813312,"name":"Roed Odegaard Port"},"name":"SideWinder","alive":true,"id":14}}}
Python代码:
^{pr2}$错误:
>>> shipYard()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "arg_test_ship.py", line 7, in shipYard
ships = [item["name"] for item in data['ships']]
TypeError: string indices must be integers
您缺少的问题是data['ships']本身就是另一个dictionary对象。当您像在shipYard()中那样遍历字典时,您只会得到键:
^{1}$您想要访问字典中的name属性,为此您将使用字典.items()方法:
^{pr2}$或者,如果不需要索引,请使用dictionary values()方法:
相关问题 更多 >
编程相关推荐