[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)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)
2023-02-26 【806】虾神-热点分析
2020-02-26 【461】word图片高清转成pdf
2013-02-26 【100】新学年的学习安排