- Rules
- Python → to JSON string → json.dumps()
- Python → to JSON file → dump()
- JSON string → to Python dict → loads()
- JSON file → to Python dict → load()
- References
https://jsonlint.com
Rules
- From/to Python dict/list, to/from json object/array
- JSON is purely string! Proved
- Double quotes only (around strings and property (keys) names)
- Don’t put extra comma or {} in the end
- When loading from json string which is big array, Python will be list and vice versa
- If you want to use JSON array, you don’t need to enclose list {[ ← wrong
- ERRORs, REMEMBER about lists [{ ← correct
‣
‣
‣
Python → to JSON string → json.dumps()
json.dumps(dict, indent=2, sort_keys=True) method can convert a Python object into a JSON string.
dictionary = {"id": "04", "name": "sunil", "department": "HR", "salary": None}
json_string = json.dumps(dictionary, indent=4)
print(json_string)Python → to JSON file → dump()
json.dump(dict, file_pointer) method can be used for writing to JSON file.
file pointer – pointer of the file opened in write or append mode.
dictionary = {"name" : "sathiyajith", "rollno" : 56, "cgpa" : 8.6, "phonenumber" : "9976770500"}
with open("sample.json", "w") as f:
json.dump(dictionary, f)
"""
# We can do also
json_string = json.dumps(dictionary, indent=2)
with open("sample.json", "w") as f:
f.write(json_string)
"""JSON string → to Python dict → loads()
json.loads(s) method can be used to parse a valid JSON string and convert it into a Python Dictionary.
s: Deserialize str instance containing a JSON document to a Python dict.
JSON file → to Python dict → load()
json.load(fp) takes a file object and returns the json object. It is used to read JSON encoded data from a file and convert it into a Python dictionary and deserialize a file itself.
fp: File pointer to read text.
# data_file.json already exists
with open("data_file.json", "r") as f:
dictionary = json.load(f)
print(dictionary)References
- https://www.geeksforgeeks.org/python-difference-between-json-dump-and-json-dumps
- https://www.geeksforgeeks.org/python-difference-between-json-load-and-json-loads
- https://www.youtube.com/watch?v=jABj-SEhtBc
- https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/JSON