Python Tutorials
Create Json in Python
JSON (JavaScript Object Notation) is a format for structuring data. It is mainly used for storing and transferring data between the client and the server. Python supports JSON with a built-in package called json. This package provides all the necessary tools for working with JSON Objects including serializing, deserializing, parsing, and more.
Let’s see a simple exampleof converting the JSON objects to Python objects and vice-versa.
Table of Contents
Example Python:
import json # JSON string user = '{"userid":"ram06", "username": "Ram", "useremail":"sriram06@gmail.com"}' # Convert string to Python dict user_dict = json.loads(user) print("User Dictionary: \n",user_dict) print("\n") # Convert Python dict to JSON json_obj = json.dumps(user_dict, indent=1) print("Final Json: \n",json_obj)
Output:
User Dictionary:
{'userid': 'ram06', 'username': 'Ram', 'useremail': 'sriram06@gmail.com'}
Final Json:
{
"userid": "ram06",
"username": "Ram",
"useremail": "sriram06@gmail.com"
}
You can convert Python objects of the subsequent types, into JSON strings:
- dict
- list
- tuple
- string
- int
- float
- True
- False
When converting from Python to JSON, Python objects are converted into the JSON (JavaScript) equivalent:
dict | Object |
list | Array |
tuple | Array |
str | String |
int | Number |
float | Number |
True | true |
False | false |