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.

Example Python:
import json

# JSON string
user = '{"userid":"ram06", "username": "Ram", "useremail":"[email protected]"}'

# 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': '[email protected]'}


Final Json: 
 {
 "userid": "ram06",
 "username": "Ram",
 "useremail": "[email protected]"
}

You can convert Python objects of the subsequent types, into JSON strings:

  1. dict
  2. list
  3. tuple
  4. string
  5. int
  6. float
  7. True
  8. False

When converting from Python to JSON, Python objects are converted into the JSON (JavaScript) equivalent:

dictObject
listArray
tupleArray
strString
intNumber
floatNumber
Truetrue
Falsefalse

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button
close