How do I save a list of python dictionaries to a file, where each dict
will be saved in one line? I know I can use json.dump
to save the list of dictionaries. But I can only save the list in compact form (the full list in one line) or indented, where for all dictionaries keys a newline is added.
EDIT:
I want my final json file to look like this:
[{key1:value,key2:value},
{key1:value,key2:value},
...
{key1:value,key2:value}]
Your final
file.json
example is not a valid JSON. Assuming you want to just convey the form with it you might try extending thejson.JSONEncoder
, but assuming you don't have nested structures in your dictionaries a quick and dirty approach would be to just construct the file manually, i.e.Which will produce:
I agree with another response -- the best you can do is to
json.dump
eachdict
individually and write the commas and newlines manually. Here is how I would do that:Result:
For fun I adapted my answer to another somewhat related question to make it do what you want. Note that currently it only changes the formatting of a
dict
if it's in a list.Sample usage:
Output:
This may not generate exactly what the OP wanted, but to pretty print JSONs generally, you can add an indent argument:
json.dump(data, json_path.open("w"), indent=2)
Example output:
This converts a 1-line dictionary to one where each key/subelement has it's own line. You can also change the "separators" command to alter how lines are split, see https://docs.python.org/3.7/library/json.html#basic-usage.