(Data: http://paste.ubuntu.com/7605667/)
I'm trying to create a json object from a txt file and print it as a list of python dicts. The code I'm using is:
records=[json.loads(line) for line in open(path)]
records[0]
This gives me:
{u'a': u'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.78 Safari/535.11', u'c': u'US', u'nk': 1, u'tz': u'America/New_York', u'gr': u'MA', u'g': u'A6qOVH', u'h': u'wfLQtf', u'cy': u'Danvers', u'l': u'orofrog', u'al': u'en-US,en;q=0.8', u'hh': u'1.usa.gov', u'r': u'http://www.facebook.com/l/7AQEFzjSi/1.usa.gov/wfLQtf', u'u': u'http://www.ncbi.nlm.nih.gov/pubmed/22415991', u't': 1331923247, u'hc': 1331822918, u'll': [42.576698, -70.954903]}
But when I use pprint, I get the desired results:
pprint(records[0])
{u'a': u'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.78 Safari/535.11',
u'al': u'en-US,en;q=0.8',
u'c': u'US',
u'cy': u'Danvers',
u'g': u'A6qOVH',
u'gr': u'MA',
u'h': u'wfLQtf',
u'hc': 1331822918,
u'hh': u'1.usa.gov',
u'l': u'orofrog',
u'll': [42.576698, -70.954903],
u'nk': 1,
u'r': u'http://www.facebook.com/l/7AQEFzjSi/1.usa.gov/wfLQtf',
u't': 1331923247,
u'tz': u'America/New_York',
u'u': u'http://www.ncbi.nlm.nih.gov/pubmed/22415991'}
How can this be done with json.loads? I tried using "records[0].split(',')" but keep getting the error message:
AttributeError: 'dict' object has no attribute 'split'
The pretty-print output is not a list of dicts; it's the same dict as what you got with a regular print, just displayed with the keys sorted and each key-value pair on its own line.
If you want to print a list of dicts, as you say, you probably want
If you want to go through the key-value pairs of each dict, you can loop over their
iteritems()
:If you don't have a solid understanding of what you want to do, figuring that out should be step 1.