Reputation: 1368
I have a python crawler that obtains json data and java program that uses this data. My approach was to serialize the json data into a file. It was represented in python as a dictionary and I did:
mails_file.write(str(email)+'\n')
which will yield a result such as:
{u'from': u'Brian Yablonski <[email protected]>', u'dateCentral': u'1999-01-05T07:33:06-06:00', u'to': u'"\'[email protected]\'" <[email protected]>', u'date': u'Tue, 5 Jan 1999 08:33:06 -0500', u'message': u"Missed the deadline, but I would have said the speech is a first step \ntoward restoring the rightful place of communities and families as the \nfirst source of ideas and solutions to our society's problems and to show \nthat government can work not as a master of, but a partner with, these \ninstitutions.\n\n-----Original Message-----\nFrom:\tJeb Bush [SMTP:[email protected]]\nSent:\tMonday, January 04, 1999 3:44 PM\nTo:\tYablonski Brian\nSubject:\tFW: Speech\n\nHow would you describe the speech for Mark?\n\n-----Original Message-----\nFrom:\tMark Silva [mailto:[email protected]]\nSent:\tMonday, January 04, 1999 3:14 PM\nTo:\[email protected]\nSubject:\tSpeech\n\nHave a quick thematic description for me about what you hope to accomplish\nwith tomorrow's inaugural address? (If you see this note before 6:30). If\nnot, thanks anyway and I wish you well Tuesday.", u'id': u'[email protected]', u'subject': u'RE: Speech'}
then I want to do some python-java format adjustments such as :
line = line.replace('u"', '"')
line = line.replace("u'", '"')
line = line.replace("'", '"')
And finally load the JSON objects in java using:
JSONObject lineJson = new JSONObject(line);
This approach fails on 95% of my objects, due python's interchangeable use of "
& '
chars. How can I overcome this problem and write a format conversion function that will actually work?
Upvotes: 1
Views: 944
Reputation: 31339
You need to use the json
module or an equivalent:
import json
# ...
json.dump(email, mails_file)
From the documentation about json.dump
:
Serialize obj as a JSON formatted stream to fp (a .write()-supporting file-like object) using this conversion table.
Upvotes: 2