Convert from Python to JSON
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 |
Converting to JSON string
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: Converting Python dictionary to JSON string
Python3
# Python program to convert # Python to JSON import json # Data to be written dictionary = { "name" : "sunil" , "department" : "HR" , "Company" : 'GFG' } # Serializing json json_object = json.dumps(dictionary) print (json_object) |
{"name": "sunil", "department": "HR", "Company": "GFG"}
Note: For more information about converting JSON to string, refer to Python – Convert to JSON string
Writing to a JSON file
dump() method can be used for writing to JSON file.
Syntax:
json.dump(dict, file_pointer)
It takes 2 parameters:
- dictionary: name of a dictionary which should be converted to a JSON object.
- file pointer: pointer of the file opened in write or append mode.
Example: Writing to JSON File
Python3
# Python program to write JSON # to a file import json # Data to be written dictionary = { "name" : "Nisha" , "rollno" : 420 , "cgpa" : 10.10 , "phonenumber" : "1234567890" } with open ( "sample.json" , "w" ) as outfile: json.dump(dictionary, outfile) |
Output:
JSON with Python
JSON (JavaScript Object Notation) is a file that is mainly used to store and transfer data mostly between a server and a web application. It is popularly used for representing structured data. In this article, we will discuss how to handle JSON data using Python. Python provides a module called json which comes with Python’s standard built-in utility.
Note: In Python, JSON data is usually represented as a string.