Unable to loop through a list of dict in python -
i have dict follows:
{ u'has_more': false, u'is_limited': true, u'latest': u'1501149118.071555', u'messages': [ { u'text': u'--sharp 1.9 dm\n--modifying , testing dm script bypassing existing sonumber validation , add line items', u'ts': u'1501149054.047400', u'type': u'message', u'user': u'u0hn06zb9'}, { u'text': u'-- support engineering on licensing infra upgrade 3.6\n - created new key qa on current 3.5 ubuntu 12 instance\n - added key instance , created ami , shared qa\n - short discussion navin on same', u'ts': u'1501148934.002719', u'type': u'message', u'user': u'u02rrqjg1'}, { u'inviter': u'u03fe3z7d', u'subtype': u'channel_join', u'text': u'<@u0hn06zb9|shikhar.rastogi> has joined channel', u'ts': u'1501148921.998107', u'type': u'message', u'user': u'u0hn06zb9'}, { u'inviter': u'u03fe3z7d', u'subtype': u'channel_join', u'text': u'<@u02rrqjg1|himani> has joined channel', u'ts': u'1501148328.777625', u'type': u'message', u'user': u'u02rrqjg1'}, { u'text': u'something ^^^^', u'ts': u'1501148318.773838', u'type': u'message', u'user': u'u03fe3z7d'}, { u'text': u'-- test \n-- not\n-- test1\n-- test b', u'ts': u'1501148309.770614', u'type': u'message', u'user': u'u03fe3z7d'}, { u'text': u'<!channel> can of start putting random crap in same format shift handoff', u'ts': u'1501148287.762336', u'type': u'message', u'user': u'u03fe3z7d'}, { u'text': u'<!channel> can of start putting random crap in same format shift handoff', u'ts': u'1501148287.762161', u'type': u'message', u'user': u'u03fe3z7d'}, { u'text': u'sjvnsv', u'ts': u'1501138569.469475', u'type': u'message', u'user': u'u03fe3z7d'}, { u'text': u'-- test1 \n-- leave asap', u'ts': u'1501136157.933720', u'type': u'message', u'user': u'u03fe3z7d'}, { u'bot_id': u'b19lzg1a5', u'subtype': u'bot_message', u'text': u'this crazy', u'ts': u'1501075281.418010', u'type': u'message', u'username': u'test_bot'}], u'ok': true, u'oldest': u'1500820472.964970'}
now trying extract 2 things 1st user
, corresponding text
, somehow not able using following :
json_objects = json.loads(r.text) in json_objects: print json_objects['messages'][i]['user'] print json_objects['messages'][i]['text']
the above throws error :
traceback (most recent call last): file "clean_test.py", line 45, in <module> get_channel_messages() file "clean_test.py", line 38, in get_channel_messages print json_objects['messages'][i]['user'] typeerror: list indices must integers, not unicode
the above should user
, calls user_detail() meathod name , come back, once done, want content dumped file in following manner
username1: -- text username2: -- text2
you want iterate on indices of list, not iterate on keys of outer dict
json_objects = json.loads(r.text) in range(len(json_objects['messages'])): print json_objects['messages'][i]['user'] print json_objects['messages'][i]['text']
or way (the pythonic way):
for in json_objects['messages']: print i['user'] print i['text']
Comments
Post a Comment