Using JSON with Python

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)

In [31]:
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)
Type: <class 'dict'> 
Content: {'Name': 'Ali', 'Age': 3, 'Member': False, 'Salary': None, 'Hobbies': ['Football', 'swimming']}

Type: <class 'str'> 
Content: {"Name": "Ali", "Age": 3, "Member": false, "Salary": null, "Hobbies": ["Football", "swimming"]}

Notice the change of False to false and None to null

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)

In [41]:
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])
Type: <class 'str'> 
Content: [1, 2, 3, 4]

Type: <class 'list'> 
Content: [1, 2, 3, 4]

Type: <class 'int'> 
Content: 1

1. Converting between JSON file objects and Python data types

1.1 dump Python data types into JSON file objects using json.dump()

In [43]:
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()

In [46]:
with open("people.json") as json_file:
    newPerson = json.load(json_file)
print(newPerson)
{"Name": "Ali", "Age": 3, "Member": false, "Salary": null, "Hobbies": ["Football", "swimming"]}

Make JSON text readable

1. Add indentation

In [50]:
jsonStr = json.dumps(person, indent=4)
print(jsonStr)
{
    "Name": "Ali",
    "Age": 3,
    "Member": false,
    "Salary": null,
    "Hobbies": [
        "Football",
        "swimming"
    ]
}

2. Sort

In [52]:
jsonStr = json.dumps(person, indent=4, sort_keys=True)
print(jsonStr)
{
    "Age": 3,
    "Hobbies": [
        "Football",
        "swimming"
    ],
    "Member": false,
    "Name": "Ali",
    "Salary": null
}