Serializing JSON files with newlines in Python

I sometimes use json and jsonpickle to serialize objects in 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 the dictionary, for example, using "json_serialize (mydict, myfilename)", then all serialization will be placed on one line. This means that I cannot smooth the file for records that will be checked manually, for example, a CSV file. Is there a way to make sure that each element of the object (for example, each entry in the dict or each element in the list) is placed on a separate line in the output JSON file?

thank.

+3
source share
2

(simple)json.dump() indent. jsonpickle , - , .

+3

Jsonpickle json-, :

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

Source: https://habr.com/ru/post/1741702/


All Articles