Read, Write and Parse JSON using Python

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:

  • 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",
         "depatment": "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:

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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'])

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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()

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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.
filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)

chevron_right


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

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.