繁体   English   中英

TypeError:字符串索引必须是整数 - 解析JSON

[英]TypeError: string indices must be integers - Parsing JSON

我在使用以下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

你缺少的问题是数据['船''本身就是另一个字典对象。 当您在shipYard()中迭代字典时,您将获得键:

>>> a={'a':1,'b':2}
... [i for i in a]
7: ['a','b']

您想要访问字典中的名称属性WITHIN,您将使用dictionary.items()方法:

>>> data = '''{"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}}}'''
... import json
... data = json.loads(data)
>>> ships = [item['name'] for index, item in data['ships'].items()]
>>> ships
8: [u'Viper_MkIV', u'SideWinder', u'Asp', u'Type7', u'SideWinder']
>>> 

或者,如果您不需要索引,请使用字典值()方法:

>>> ships = [item['name'] for item in data['ships'].values()]
>>> ships
9: [u'Viper_MkIV', u'SideWinder', u'Asp', u'Type7', u'SideWinder']
>>> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM