Nikhil Prabhu Nikhil Prabhu - 5 months ago 24
Python Question

How do I dump and load multiple python objects into and from a json file?

I want to store several variables in a json file.

I know I can dump multiple variable like this-

import json
with open('data.json', 'w') as fp:
json.dump(p_id,fp, sort_keys = True, indent = 4)
json.dump(word_list, fp, sort_keys = True, indent = 4)
.
.
.


But these variables are stored without their names and trying to load them gives errors. How do I store and extract the variables I want appropriately?

Answer

You'd generally write one JSON object to a file; that object can contain your other objects:

json_data = {
    'p_id': p_id,
    'word_list': word_list,
    # ...
}
with open('data.json', 'w') as fp:
    json.dump(json_data, fp, sort_keys=True, indent=4)

Now all you have to do is read that one object and address the values by the same keys.

If you must write multiple JSON documents, avoid using newlines so you can read the file line by line, as parsing the file one JSON object at a time is a lot more involved.