json_read_and_write.py 590 B

1234567891011121314151617181920212223242526272829
  1. #! /usr/bin/env python3
  2. # Write and read json files
  3. #
  4. # See https://www.geeksforgeeks.org/reading-and-writing-json-to-a-file-in-python/
  5. #
  6. import json
  7. # make a random dictionary
  8. foo_dict={}
  9. foo_dict["bar"] = "A bar"
  10. foo_dict["baz"] = "A baz"
  11. print(f"foo_dict: {foo_dict}")
  12. # create json a string
  13. foo_json = json.dumps(foo_dict,indent=4)
  14. print(f"foo_json: {foo_json}")
  15. # save it to a file
  16. with open("sample.json", "w") as outfile:
  17. outfile.write(foo_json)
  18. # read it back
  19. with open('sample.json', 'r') as openfile:
  20. bar_json = json.load(openfile)
  21. print(f"bar_json: {bar_json}")