Python 2迭代嵌套的json字典

时间:2022-03-23 14:31:22

I have a dict sourced from documents in Elasticsearch with JSON that looks like this:

我有一个源自Elasticsearch中带有JSON的文档的dict,如下所示:

{  
   u'hits':{  
      u'hits':[  
         {  
            u'_score':1.0,
            u'_type':u'input',
            u'_id':u'1',
            u'_source':{  
               u'message':u'I really love fake news tho.'
            },
            u'_index':u'gossip'
         }
      ],
      u'total':1,
      u'max_score':1.0
   },
   u'_shards':{  
      u'successful':1,
      u'failed':0,
      u'total':1
   },
   u'took':3,
   u'timed_out':False
}

There are several thousand documents and I am looking to get a list of each of the 'message' values. I have tried several approaches but cannot seem to get a functioning solution. My current attempt is:

有几千个文档,我希望得到每个'消息'值的列表。我尝试了几种方法但似乎无法获得有效的解决方案。我目前的尝试是:

messages = es.search(index="gossip", _source=['message'])
for key, value in messages.iteritems():
    print key, value

which results in:

这导致:

hits{  
   u'hits':[  
      {  
         u'_score':1.0,
         u'_type':u'input',
         u'_id':u'1',
         u'_source':{  
            u'message':u'I really love fake news tho.'
         },
         u'_index':u'gossip'
      }
   ],
   u'total':1,
   u'max_score':1.0
}_shards{  
   u'successful':1,
   u'failed':0,
   u'total':1
}

Hoping somebody can nudge me in the right direction.

希望有人能够朝着正确的方向推动我。

1 个解决方案

#1


0  

Try this -

尝试这个 -

es_res = {  
   u'hits':{  
      u'hits':[  
         {  
            u'_score':1.0,
            u'_type':u'input',
            u'_id':u'1',
            u'_source':{  
               u'message':u'I really love fake news tho.'
            },
            u'_index':u'gossip'
         }
      ],
      u'total':1,
      u'max_score':1.0
   },
   u'_shards':{  
      u'successful':1,
      u'failed':0,
      u'total':1
   },
   u'took':3,
   u'timed_out':False
}

print [ i['_source']['message'] for i in es_res['hits']['hits']]

#1


0  

Try this -

尝试这个 -

es_res = {  
   u'hits':{  
      u'hits':[  
         {  
            u'_score':1.0,
            u'_type':u'input',
            u'_id':u'1',
            u'_source':{  
               u'message':u'I really love fake news tho.'
            },
            u'_index':u'gossip'
         }
      ],
      u'total':1,
      u'max_score':1.0
   },
   u'_shards':{  
      u'successful':1,
      u'failed':0,
      u'total':1
   },
   u'took':3,
   u'timed_out':False
}

print [ i['_source']['message'] for i in es_res['hits']['hits']]