2014-03-14 82 views
0

我有一個JSON輸出像下面,如何迭代python中的json數據?

{ 
"took":3,"timed_out":false,"_shards":{"total":5,"successful":5,"failed":0}, 
"hits":{"total":2,"max_score":1.0, 
"hits": 
[ 
{ 
    "_index":"management", 
    "_type":"", 
    "_id":"/home/myfld1/myid1", 
    "_score":1.0, 
    "_source" : 
    { 
     "newslides": "User Mgmt1 ", 
     "metaData": 
     { 
      "fileName": "file1", 
     } 
    } 
    }, 
    { 
     "_index":"management", 
     "_type":"", 
     "_id":"/home/myfld3/myid3", 
     "_score":1.0, 
     "_source" : 
     { 
      "newslides": "User mgmt2 ", 
      "metaData": 
      { 
       "fileName": "file2", 
      } 
     } 
    } 
] 
} 
} 

我想從上面的JSON得到「文件名」字段中。我已經試過這樣的,

for filenames in response["hits"]["hits"][0]["_source"]["newslides"]["metaData"]: 
     filearray.append(filenames["fileName"]) 

但我得到一個錯誤,如下面,

for filenames in response["hits"]["hits"][0]["_source"]["newslides"]["metaData"]: 
TypeError: string indices must be integers 

請幫我得到那個文件名。

+0

你有'[「newslides」]'它不應該存在。否則,請參閱我的答案。 – sashkello

回答

0

它只是一個包含一些列表和其他字典的字典。只是要小心,並經過反覆的元素:

filearray = [] 
for x in response["hits"]["hits"]: 
    filearray.append(x["_source"]["metaData"]["fileName"]) 

或一條線:

filearray = [x["_source"]["metaData"]["fileName"] for x in response["hits"]["hits"]]