[981] JSON module in Python
In Python, the json
module provides functions for encoding and decoding JSON data. Here's a brief explanation of the commonly used functions:
json.dump()
andjson.load()
are functions for file processing.json.dumps()
andjson.loads()
are functions for variable processing.dump(s)
: dict -> stringload(s)
: string -> dict
-
json.dumps()
: This function is used to serialize Python objects to a JSON formatted string. It takes a Python object (such as a dictionary or a list) as input and returns a JSON formatted string.Example:
import json data = {'name': 'John', 'age': 30, 'city': 'New York'} json_string = json.dumps(data) print(json_string)
-
json.dump()
: This function is similar tojson.dumps()
, but it writes the JSON data directly to a file-like object (such as a file object opened in write mode). It serializes the Python object to JSON and writes it to the specified file.Example:
import json data = {'name': 'John', 'age': 30, 'city': 'New York'} with open('data.json', 'w') as json_file: json.dump(data, json_file)
-
json.loads()
: This function is used to deserialize a JSON formatted string into a Python object. It takes a JSON formatted string as input and returns a Python object (such as a dictionary or a list).Example:
import json json_string = '{"name": "John", "age": 30, "city": "New York"}' data = json.loads(json_string) print(data)
-
json.load()
: This function is similar tojson.loads()
, but it reads JSON data from a file-like object (such as a file object opened in read mode) and deserializes it into a Python object.Example:
import json with open('data.json', 'r') as json_file: data = json.load(json_file) print(data)