Explorar el Código

Add example to read and write json

George Jones hace 1 año
padre
commit
3eaf102134
Se han modificado 1 ficheros con 29 adiciones y 0 borrados
  1. 29 0
      home/public/snippits/python/json_read_and_write.py

+ 29 - 0
home/public/snippits/python/json_read_and_write.py

@@ -0,0 +1,29 @@
+#! /usr/bin/env python3
+# Write and read json files
+#
+# See https://www.geeksforgeeks.org/reading-and-writing-json-to-a-file-in-python/
+#
+
+import json
+
+# make a random dictionary
+foo_dict={}
+foo_dict["bar"] = "A bar"
+foo_dict["baz"] = "A baz"
+
+print(f"foo_dict: {foo_dict}")
+
+# create json a string
+foo_json = json.dumps(foo_dict)
+
+print(f"foo_json: {foo_json}")
+
+# save it to a file
+with open("sample.json", "w") as outfile:
+    outfile.write(foo_json)
+
+# read it back
+with open('sample.json', 'r') as openfile:
+    bar_json = json.load(openfile)
+ 
+print(f"bar_json: {bar_json}")