in this tutorial, I’ll demonstrate about load JSON file in python. You can also learn about python json.load()
and json.loads()
methods to read JSON data from a file and String.
You can also checkout other python file tutorials:
- How To Create and Write JSON file in Python
- How To Read Write Yaml File in Python3
- Write Text File Using Python 3
- Extract Text From PDF File Using Python
- Merging pdf Files Using Python
How To Decode JSON in Python
You can convert JSON encoded/formatted data into Python Types, this process is known as JSON decoding. Python built-in module JSON provides the following two methods to decode JSON data.
- json.load() : This method is used to parse JSON from URL or file.
- json.loads() : This method is used to parse string with JSON content.
Mapping between JSON and Python entities
The following conversion table, which is used by the json.load()
and json.loads()
method for the translations in decoding.
JSON | Python |
---|---|
object | dict |
array | list |
string | str |
number (int) | int |
number (real) | float |
true | True |
false | False |
null | None |
json.load() Example
The json.load()
is used to read the JSON document from file and convert it into a dictionary.The json.load()
method returns a Python dictionary containing data. This dictionary is also used to access and alter data in our application or system. The syntax of json.load()
method:
json.load(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
Let’s read the json file(employee.json
) file. This file contains the following JSON data.
{ "firstName": "Adam", "lastName": "Joe", "gender": "man", "age": 24, "address": { "streetAddress": "26", "city": "San Jone", "state": "CA", "postalCode": "394221" }, "phoneNumbers": [ { "type": "home", "number": "00000000001" } ] }
The python code to read JSON file:
import json print("Started Reading JSON file") with open("employee.json", "r") as read_file: print("Starting to convert json decoding") emps = json.load(read_file) print("Decoded JSON Data From File") for key, value in emps.items(): print(key, ":", value) print("Done reading json file")
The Output:
Started Reading JSON file Starting to convert json decoding Decoded JSON Data From File firstName : Adam lastName : Joe gender : man age : 24 address : {'streetAddress': '26', 'city': 'San Jone', 'state': 'CA', 'postalCode': '394221'} phoneNumbers : [{'type': 'home', 'number': '00000000001'}] Done reading json file
json.loads() to convert JSON string to a dictionary
The json.loads()
method is used to convert json string into python dictionary. The syntax of json.load()
method:
json.loads(s, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
Let’s read the JSON string data and parse it into the python using json.loads()
method.
import json jsonStringData = """{ "firstName": "Adam", "lastName": "Joe", "gender": "man", "age": 24, "address": { "streetAddress": "26", "city": "San Jone", "state": "CA", "postalCode": "394221" }, "phoneNumbers": [ { "type": "home", "number": "00000000001" } ] }""" print("Started converting JSON string document to Python dictionary") empDict = json.loads(jsonStringData) print("Printing key and value") print(empDict["firstName"]) print(empDict["lastName"]) print(empDict["gender"]) print(empDict["age"])
Output:
Started converting JSON string document to Python dictionary Printing key and value Adam Joe man 24
Parse and Retrieve nested JSON array key-values
We can also access nested JSON key using python, I am accessing the above nested JSON data into python as below:
print("Phone Numbers: ", empDict["address"][0]["name"]) print("Address: ", empDict["address"]["streetAddress"])