0

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?

1
  • Assuming you had the dict {'variable_1': 'something'}, would you want the output file to contain "variable_1": "something" or variable_1: something. Without the quotes it is not JSON. Commented Dec 5, 2012 at 17:28

1 Answer 1

3

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"
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, but this inserts new lines within each object as well (e.g. if variable_1 is a list, it will also insert new lines between every pair of items in the list). Is there a way to have new lines only between variables?
@user273158: no, there isn't. You'd have to use .dumps() to dump to a string, then post-process before writing the result out to your file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.