4

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?

2
  • Why not dump them in different files that correspond to the name of the objects? Commented Jul 2, 2016 at 9:25
  • Or put them in an outer dictionary where the key is the name. Could you give a less abstract example? A minimal reproducible example is more helpful than "gives errors". Commented Jul 2, 2016 at 9:26

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

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.