3

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?

Nikhil Prabhu
  • 1,072
  • 3
  • 12
  • 24

1 Answers1

7

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343