This python tutorial help to read JSON file using python json libs.The json help to communicate data between server and client. In this article, we’ll explore how we can parse JSON files with python’s inbuilt JSON module.
What’s JSON
The file format JSON stands for JavaScript Object Notation and is used to store data. JSON files are similar to dictionaries in Python. During deployment, they help in data storage and communication with servers.
Python json Module Methods
There are some of the useful functions provided by the json module are included in the following table. We can serialize and deserialize with only one line of code using these!.
- json.load(fileObject) : This method is used to parse JSON from URL or file.
- json.loads(string) : This method is used to parse string with JSON content.
- json.dump(dictionary, fileObject) : Writes the contents of the python dictionary as json objects into the provided file object (serialization)
Difference Between json.load() and json.loads() functions
I’ll demonstrate reading a json file or string json data into python dictionaries.The difference between json.load()
and json.loads()
:
- json.load(): This method expects a json file (file object) – e.g. a file you opened before given by filepath like
'employee.json'
. - json.loads(): This takes a STRING json.loads() expects a (valid) JSON string – i.e.
{"employee_name": "rachel"}
.
You can also love to read other python 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
The following conversion table, which is used by the json.load() and json.loads() method for the translations in decoding.
JSON Objects | Python Equivalent |
---|---|
Object | Dictionary (dict) |
Array | List (list) |
String | String (str) |
Number | Integer (int), Float (float) |
Boolean true | True |
Boolean false | False |
Null | None |
Read json File In Python
Let’s read a JSON file and convert it into python dictionaries using json.load()
method.
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)
How to Open and Read JSON Files in Python?
We’ll implement the code to open, read and traverse the .json
file:
- Open the json file using the open() method
- We’ll use the json.load() function and pass the file object
- The result as a normal python dictionary, and print the contents!
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 source code to read json file in python:
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")
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
How To Convert JSON String Into Python Dict
The json.loads() method is used to convert json string into a 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)
Below is a sample python code to convert json string into python dict.
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