Read, Write and Parse JSON using Python

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:
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"
      }
   ]
}
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 stringemployee ='{"id":"09", "name": "Nitin", "department":"Finance"}'  # Convert string to Python dictemployee_dict = json.loads(employee)print(employee_dict)  print(employee_dict['name'])
Output: 
{'id': '09', 'department': 'Finance', 'name': 'Nitin'}
Nitin
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.
We want to read the content of this file. Below is the implementation.
Python3
# Python program to read# json file      import json   # Opening JSON filef = open('data.json',)   # returns JSON object as # a dictionarydata = json.load(f)   # Iterating through the json# listfor i in data['emp_details']:    print(i)   # Closing filef.close()
Output:
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.
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 writtendictionary ={  "id": "04",  "name": "sunil",  "department": "HR"}   # Serializing json json_object = json.dumps(dictionary, indent = 4)print(json_object)
{
    "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:
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 writtendictionary ={    "name" : "sathiyajith",    "rollno" : 56,    "cgpa" : 8.6,    "phonenumber" : "9976770500"}   with open("sample.json", "w") as outfile:    json.dump(dictionary, outfile)
Output:
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.
gulshankumarar231
Python-json
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.