Python read JSON file
Let’s suppose we have a JSON file that looks like this.
Here, we have used the open() function to read the JSON file. Then, the file is parsed using json.load() method which gives us a dictionary named data.
Python3
import json # Opening JSON file f = open ( 'data.json' ,) # returns JSON object as # a dictionary data = json.load(f) # Iterating through the json # list for i in data[ 'emp_details' ]: print (i) # Closing file f.close() |
Output:
Read, Write and Parse JSON using Python
JSON is a lightweight data format for data interchange that can be easily read and written by humans, and easily parsed and generated by machines. It is a complete language-independent text format. To work with JSON data, Python has a built-in package called JSON.
Example of JSON String
s = '{"id":01, "name": "Emily", "language": ["C++", "Python"]}'
The syntax of JSON is considered a subset of the syntax of JavaScript including the following:
- Name/Value pairs: Represents Data, the name is followed by a colon(:), and the Name/Value pairs are separated by a comma(,).
- Curly braces: Holds objects.
- Square brackets: Hold arrays with values separated by a comma (,).
Keys/Name must be strings with double quotes and values must be data types amongst the following:
- String
- Number
- Object (JSON object)
- array
- Boolean
- Null
Example of JSON file:
{
"employee": [
{
"id": "01",
"name": "Amit",
"department": "Sales"
},
{
"id": "04",
"name": "sunil",
"department": "HR"
}
]
}