Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Read, Write and Parse JSON using Python

  • Difficulty Level : Expert
  • Last Updated : 18 Aug, 2021

JSON is a lightweight data format for data interchange which can be easily read and written by humans, 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:
s = '{"id":01, "name": "Emily", "language": ["C++", "Python"]}'

The syntax of JSON is considered as a subset of the syntax of JavaScript including the following:

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

  • Name/Value pairs: Represents Data, name is followed by ‘:'(colon) and the Name/Value pairs separated by, (comma).
  • Curly braces: Holds objects.
  • Square brackets: Hold arrays with values separated by, (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:
 {
   "employee": [

      {
         "id": "01",
         "name": "Amit",
         "department": "Sales"
      },

      {
         "id": "04",
         "name": "sunil",
         "department": "HR"
      }
   ]
}

Parse JSON (Convert from JSON to Python)

json.loads() method can parse a json string and the result will be a Python dictionary.
Syntax:

json.loads(json_string)

Example:

Python3




# Python program to convert JSON to Python
  
  
import json
  
# JSON string
employee ='{"id":"09", "name": "Nitin", "department":"Finance"}'
  
# Convert string to Python dict
employee_dict = json.loads(employee)
print(employee_dict)
  
print(employee_dict['name'])


Output:
 

{'id': '09', 'department': 'Finance', 'name': 'Nitin'}
Nitin

Python read JSON file

json.load() method can read a file which contains a JSON object. Consider a file named employee.json which contains a JSON object.
Syntax:

json.load(file_object)

Example: Let’s suppose the JSON looks like this.

pyhton-append-json1

We want to read the content of this file. Below is the implementation.

Python3






# Python program to read
# json file
   
   
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:

python-read-json-output1

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.

Convert from Python to JSON

json.dumps() method can convert a Python object into a JSON string. 
Syntax:

json.dumps(dict, indent)

It takes two parameters:

  • dictionary – name of dictionary which should be converted to JSON object.
  • indent – defines the number of units for indentation

Example:
 

Python3




# Python program to convert
# Python to JSON
   
   
import json
   
# Data to be written
dictionary ={
  "id": "04",
  "name": "sunil",
  "department": "HR"
}
   
# Serializing json 
json_object = json.dumps(dictionary, indent = 4)
print(json_object)


Output

{
    "id": "04",
    "name": "sunil",
    "department": "HR"
}

Output:
 

{
    "depatment": "HR",
    "id": "04",
    "name": "sunil"
}

The following types of Python objects can be converted into JSON strings: 
 

  • dict
  • list
  • tuple
  • string
  • int
  • float
  • True
  • False
  • None

Python objects and their equivalent conversion to JSON:

Python JSON Equivalent
dict object
list, tuple array
str string
int, float number
True true
False false
None null

Writing JSON to a file

json.dump() method can be used for writing to JSON file.
Syntax:

json.dump(dict, file_pointer)

It takes 2 parameters:

  • dictionary – name of dictionary which should be converted to JSON object.
  • file pointer – pointer of the file opened in write or append mode.

Python3




# Python program to write JSON
# to a file
   
   
import json
   
# Data to be written
dictionary ={
    "name" : "sathiyajith",
    "rollno" : 56,
    "cgpa" : 8.6,
    "phonenumber" : "9976770500"
}
   
with open("sample.json", "w") as outfile:
    json.dump(dictionary, outfile)


Output:

python-json-write-to-file

The above program opens a file named sample.json in writing mode using ‘w’. The file will be created if it does not exist. Json.dump() will transform dictionary to a JSON string and it will be saved in the file sample.json.




My Personal Notes arrow_drop_up
Recommended Articles
Page :