How to write simplejson in python 2.4

523 views Asked by At

I have an issue where I need to use simplejson to write some dictionaries to file using python 2.4 (yes, we're actively trying to upgrade; no, it's not ready yet).

Python 2.4 cannot use the syntax:

with open('data.txt', 'w') as outfile:
    json.dumps(data, outfile)

and I cannot find the correct syntax anywhere. If I try using this:

sov_filename = 'myfile.txt'
sov_file     = open( sov_filename, 'w' )
filecontents = json.dumps( sov_file )

nothing happens. The file is created, but nothing is in it.

So, does anybody know how to do this for python 2.4?

3

There are 3 answers

0
roninveracity On BEST ANSWER

I simply needed to close() it. I had it in the code, but was exiting before it executed. I was accustomed to this not being necessary because I was using the csv writer in a python 2.7 script, for which the lines appear in the file without explicitly closing.

4
Delimitry On

To save JSON to file use json.dump:

sov_filename = 'myfile.txt'
sov_file = open(sov_filename, 'w')
json.dump(data, sov_file)
0
Erin Call On

The with syntax is syntactic sugar. The desugared equivalent is:

outfile = open('data.txt', 'w')
try:
    json.dump(data, outfile)
finally:
    outfile.close()

I'm not sure why simplejson isn't writing to the file, but you can work around that as well, by replacing json.dump(data, outfile) with outfile.write(json.dumps(data))