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:

  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

KSR

Hi there! I am the Founder of Cyber World Technologies. My skills include Android, Firebase, Python, PHP, and a lot more. If you have a project that you'd like me to work on, please let me know: contact@cyberworldtechnologies.co.in

Related Articles

Leave a Reply

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

Back to top button