【发布时间】:2016-02-04 21:29:03
【问题描述】:
我在使用以下 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 代码:
import json
with open('profile.txt') as edstats:
data = json.load(edstats)
def shipYard():
ships = [item["name"] for item in data['ships']]
print json.dumps(ships,indent=4)
错误:
>>> 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
【问题讨论】:
-
如果回答了您的问题,请接受答案:D