Reputation: 96284
Say I want to dump multiple variables to disk with Json. They way I usually do this is by creating my variables as entries in a dictionary and then dumping the dictionary to disk:
with open(p_out, 'wb') as fp:
json.dump(my_dictionary, fp)
This creates a json file where the dictionary is saved in a long line:
{"variable_1": something, "variable_2" something_else, ...}
which I don't like. I would prefer to have my variables dumped into the text file with one variable per line, e.g something along these lines:
{variable_1: something\n
variable_2: something\n
variable_3: something_else}
Is there a way to do this with Json in Python?
Upvotes: 0
Views: 4843
Reputation: 1121992
Set the indent
option to 0
or more:
with open(p_out, 'wb') as fp:
json.dump(my_dictionary, fp, indent=0)
From the documentation:
If indent is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0, or negative, will only insert newlines.
None
(the default) selects the most compact representation.
Your example would be output as:
{
"variable_2": "something_else",
"variable_1": "something"
}
Upvotes: 3