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

时间:2016-02-04 13:22:16

标签: python 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

1 个答案:

答案 0 :(得分:3)

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

DECLARE @t table(id int,A int,B  int,C int,Priority int)
INSERT @t
VALUES (1,NULL,3   ,4   ,1),
(1,5   ,6   ,NULL,2),(1,8   ,NULL,NULL,3),
(2,634 ,346 ,359 ,1),(2,34  ,NULL,734 ,2)

;WITH CTE as
(
  SELECT id, 
  CASE WHEN row_number() over 
    (partition by id order by Priority*power(A,0) desc) = 1 THEN A END A,
  CASE WHEN row_number() over 
    (partition by id order by Priority*power(B,0) desc) = 1 THEN B END B,
  CASE WHEN row_number() over 
    (partition by id order by Priority*power(C,0) desc) = 1 THEN C END C
  FROM @t
)
SELECT id, max(a) a, max(b) b, max(c) c
FROM CTE
GROUP BY id

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

id  a   b   c
1   8   6   4
2   34  346 734

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

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