JSON facilitates data sharing (storing) by standardizing the data format.
1. Converting between JSON stings and Python data types
1.1 Converting from Python data types to JSON strings using json.dumps()
JSON sting <-json.dumps(Python data type)
import json
def printStr(str1,str2):
"""Helper function"""
print("Type: {} \nContent: {}\n".format(str1,str2))
person = {"Name":"Ali", "Age":3, "Member":False, "Salary":None, \
"Hobbies":["Football", "swimming"]}
printStr(type(person), person)
person_data = json.dumps(person) # Python -> JSON
printStr(type(person_data), person_data)
Notice the change of
False
tofalse
andNone
tonull
Python data types (int, float, long, str, list, tuple, dict,and bool) can be in a similar way converted to JSON stings
1.2 Converting from JSON strings to Python data types using: json.loads()
Python data type <-json.dumps(JSON sting)
integers = (1,2,3,4) # Python tuple
numbers = json.dumps(integers) # Python tuple -> JSON string
printStr(type(numbers), numbers)
integers_2 = json.loads(numbers) # JSON string -> to what Python predicts (tuple of list)
printStr(type(integers_2), integers_2)
printStr(type(integers_2[0]), integers_2[0])
1. Converting between JSON file objects and Python data types
1.1 dump Python data types into JSON file objects using json.dump()
with open("people.json", "w") as json_file:
json.dump(person_data, json_file) # output to a json file
1.2 load JSON file objects to Python data types using json.load()
with open("people.json") as json_file:
newPerson = json.load(json_file)
print(newPerson)
jsonStr = json.dumps(person, indent=4)
print(jsonStr)
2. Sort
jsonStr = json.dumps(person, indent=4, sort_keys=True)
print(jsonStr)