How to make json in Python
Making JSON in Python with a simple example: learn how to use the json library to create and manipulate JSON data.
Creating JSON in Python
JSON (JavaScript Object Notation) is a lightweight data-interchange format used for exchanging data between a server and a web application. It is easy to read and write, and it is used extensively in many web applications. In Python, creating and manipulating JSON is quite straightforward and can be done with the built-in json
module.
For example, let's say we have a list of people with their names and ages:
people = [
{
"name": "John Smith",
"age": 35
},
{
"name": "Jane Doe",
"age": 28
}
]
We can convert this list into JSON using the json.dumps()
function:
import json
json_string = json.dumps(people)
print(json_string)
This will output the following JSON string:
[{"name": "John Smith", "age": 35}, {"name": "Jane Doe", "age": 28}]
We can also convert a JSON string into a Python object using the json.loads()
function:
json_string = '[{"name": "John Smith", "age": 35}, {"name": "Jane Doe", "age": 28}]'
people = json.loads(json_string)
print(people)
This will output the following list of Python objects:
[{'name': 'John Smith', 'age': 35}, {'name': 'Jane Doe', 'age': 28}]
As you can see, creating and manipulating JSON in Python is quite straightforward. With the built-in json
module, you can easily convert data between Python and JSON, making it an ideal format for exchanging data between server and web applications.