serializing JSON files with newlines in Python
Asked Answered
R

2

5

I am using json and jsonpickle sometimes to serialize objects to files, using the following function:

def json_serialize(obj, filename, use_jsonpickle=True):
    f = open(filename, 'w')
    if use_jsonpickle:
    import jsonpickle
    json_obj = jsonpickle.encode(obj)
    f.write(json_obj)
    else:
    simplejson.dump(obj, f) 
    f.close()

The problem is that if I serialize a dictionary for example, using "json_serialize(mydict, myfilename)" then the entire serialization gets put on one line. This means that I can't grep the file for entries to be inspected by hand, like I would a CSV file. Is there a way to make it so each element of an object (e.g. each entry in a dict, or each element in a list) is placed on a separate line in the JSON output file?

thanks.

Rapeseed answered 19/4, 2010 at 1:48 Comment(0)
B
6

Jsonpickle uses one of the json backends and so you can try this to your code:

jsonpickle.set_encoder_options('simplejson', sort_keys=True, indent=4)

Update: simplejson has been incorporated into base python, just replace simplejson for json and you'll get the pretty-printed/formatted/non-minified json

jsonpickle.set_encoder_options('json', sort_keys=True, indent=4)
Barbette answered 5/12, 2010 at 14:43 Comment(0)
A
5

(simple)json.dump() has the indent argument. jsonpickle probably has something similar, or in the worst case you can decode it and encode it again.

Amylo answered 19/4, 2010 at 1:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.