Python has an in-built package called JSON. So in this article we will discuss on Python JSON in details. The following is the content of this JSON :
- Convert JSON to Python
- Covert Python to JSON
- List of Objects Can be Converted to JSON
- Python & JSON object equivalent
- Format Result
- Use of sort_keys parameter
Convert JSON to Python
In order to parse JSON to Python, we use json.loads() method. The following is a code to parse
import json
a= '{ "name": "Sneha", "class":10, "section":"B"}' #json
b=json.loads(a) #parse a
print(b["class"]) #returns 10
Covert Python to JSON
json.dumps() method is used to convert Python to JSON. To know more you can refer to this site.
import json
a= {
"name": "Sneha",
"class":10,
"section":"B"
} #a Python object
b= json.dumps(a)#convert into JSON
print(b) # result is a JSON string
List of Objects Can be Converted to JSON
- list
- dict
- tuple
- string
- int
- float
- True
- False
- None
import json
print(json.dumps({"name": "Itika", "course":"Btech"}))
print(json.dumps(["mango","banana"]))
print(json.dumps(("rose", "lotus")))
print(json.dumps("Python Tutorial"))
print(json.dumps(2020))
print(json.dumps(3.14))
print(json.dumps(True))
print(json.dumps(False))
print(json.dumps(None))
Python & JSON object equivalent
Python | JSON |
dict | Object |
list | Array |
tuple | Array |
str | String |
True | true |
False | false |
int | Number |
float | Number |
None | null |
Format Result
The json.dumps() method makes the result be readable.
json.dumps(a, indent=4)
Also, the separators, default values like semicolon, commas can be used to separate keys from the values.
json.dumps(a, indent=4, separators=(". "," = "))
Use of sort_keys parameter
In json.dumps() method there is a parameter sort_keys to specify if the result is specified or not.
json.dumps(a, indent=4, sort_keys=True)