import json

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
  • Like this
  • If you want to use JSON array, you don’t need to enclose list {[ ← wrong
  • ERRORs, REMEMBER about lists [{ ← correct
  • Here
Good JSON Example

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)
Keys in JSON object is called property, and it is always string
Keys in JSON object is called property, and it is always 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

image
SuperMade with Super