2013-05-09 46 views
0

我的JSON文件漂亮的印刷:使用Python找到JSON文件隨機評論

{u'count': 80, 
u'data': [{u'comment': {u'activity_id': 41638, 
         u'date': u'4/2/2013 11:07:29 PM', 
         u'id': 3230, 
         u'message': u'I echo that. Thanks for jumping in at any moment without hesitation to take the lead on TMO deliverables; you have improved our relationship with an extremely valuable client.', 
         u'user': {u'first_name': u'Brent', 
            u'id': 4863, 
            u'last_name': u'Camalich', 
            u'picture': u'http://lunchbox.youearnedit.com/profile/4863/image/'}}}, 
      {u'comment': {u'activity_id': 42577, 
         u'date': u'4/5/2013 12:29:16 AM', 
         u'id': 3384, 
         u'message': u'Thanks Greg! Go team Gamecenter!', 
         u'user': {u'first_name': u'Malik', 
            u'id': 7581, 
            u'last_name': u'Jones', 
            u'picture': u'http://lunchbox.youearnedit.com/profile/7581/image/'}}}, 
      {u'comment': {u'activity_id': 42578, 
         u'date': u'4/5/2013 12:29:54 AM', 
         u'id': 3385, 
         u'message': u'Thanks Josh!! Appreciate the points! Let me know if you ever need anything.', 
         u'user': {u'first_name': u'Malik', 
            u'id': 7581, 
            u'last_name': u'Jones', 
            u'picture': u'http://lunchbox.youearnedit.com/profile/7581/image/'}}}], 
u'page': 1, 
u'page_count': 4, 
u'page_size': 25} 

我可以返回JSON文件的頂層部分像countpagepage_countpage_size但我掙扎得到activity_id s的清單。之後,我正計劃從列表中隨機挑選一條評論。任何幫助表示讚賞

#!/bin/python 

import requests, json 
from pprint import pprint 

comments_url = "https://lunchbox:[email protected]/comments" 
r = requests.get(comments_url) 

json_data = r.json() 

print "Comment Count" 
print json_data["count"] 

pprint(json_data) 

activity_ids = [comment['activity_id'] for comment in json_data[1]['comments']] 

for activity_id in activity_ids: 
    print activity_id 

回答

0

明白了。

for item in json_data['data']: 
    comment = item['comment'] 
    print comment['activity_id']