JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write and easy for machines to parse and generate. It is based on a subset of the JavaScript programming language and is commonly used to transmit data between a server and a web application or between two web applications.
In Python, you can use the json
module to work with JSON data. The json
module provides functions for encoding and decoding JSON data.
In Python, the json module provides functions for working with JSON. You can use the json.dumps()
method to convert a Python object into a JSON string, and the json.loads()
method to convert a JSON string into a Python object.
Here’s an example of using these methods to encode and decode a Python dictionary:
import json
# Encode a Python dictionary into a JSON string
data = {'name': 'John Smith', 'age': 30, 'city': 'New York'}
json_data = json.dumps(data)
print(json_data) # Output: {"name": "John Smith", "age": 30, "city": "New York"}
# Decode a JSON string into a Python dictionary
decoded_data = json.loads(json_data)
print(decoded_data) # Output: {'name': 'John Smith', 'age': 30, 'city': 'New York'}
You can also use the json.dump()
method to write a JSON string to a file, and the json.load()
method to read a JSON string from a file.
import json
# Write a JSON string to a file
data = {'name': 'John Smith', 'age': 30, 'city': 'New York'}
with open('data.json', 'w') as f:
json.dump(data, f)
# Read a JSON string from a file
with open('data.json', 'r') as f:
data = json.load(f)
print(data) # Output: {'name': 'John Smith', 'age': 30, 'city': 'New York'}
Comment on “Python- How to JSON”