JSON.parse()
和 JSON.stringify()
处理 JSON 数据。总结来说,JSON 的优势在于其简单、灵活、轻量和高效,广泛适用于现代的 Web 开发、API 设计以及数据存储和传输。
x = {
"name": "John",
"age": 30,
"married": True,
"divorced": False,
"children": ("Ann","Billy"),
"pets": None,
"cars": [
{"model": "BMW 230", "mpg": 27.5},
{"model": "Ford Edge", "mpg": 24.1}
]
}
y = {
"name": "John Doe",
"age": 30,
"email": "[email protected]",
"isStudent": false,
"courses": [
{
"courseName": "Mathematics",
"grade": "A"
},
{
"courseName": "Physics",
"grade": "B+"
}
],
"address": {
"street": "1234 Elm Street",
"city": "Metropolis",
"postalCode": "12345"
},
"skills": ["JavaScript", "Python", "Machine Learning"],
"experience": [
{
"company": "TechCorp",
"position": "Software Engineer",
"yearsWorked": 5
},
{
"company": "DataSolutions",
"position": "Data Analyst",
"yearsWorked": 2
}
]
}
python主要使用json
包处理JSON结构。在 Python 中,使用 JSON 数据非常方便。Python 提供了内置的 json
模块来解析(将 JSON 字符串转换为 Python 对象)和生成(将 Python 对象转换为 JSON 字符串)JSON 数据。以下是使用 JSON 数据的主要操作:
可以使用 json.loads()
函数将 JSON 字符串解析为 Python 数据类型,如字典、列表等。
import json
# JSON 字符串
json_string = '{"name": "John", "age": 30, "city": "New York"}'
# 解析 JSON 数据为 Python 字典
python_dict = json.loads(json_string)
print(python_dict)
print(python_dict["name"]) # 访问字典中的数据
{'name': 'John', 'age': 30, 'city': 'New York'}
John
可以使用 json.dumps()
函数将 Python 对象(如字典、列表等)转换为 JSON 字符串。
import json
# Python 字典
python_dict = {
"name": "John",
"age": 30,
"city": "New York"
}
# 生成 JSON 字符串
json_string = json.dumps(python_dict)
print(json_string)
{"name": "John", "age": 30, "city": "New York"}
import json
python_list = [
{"name": "John", "age": 30},
{"name": "Jane", "age": 25}
]
# 将列表转换为 JSON 字符串
json_string = json.dumps(python_list, indent=4) # 使用 indent 使输出更美观
print(json_string)
[
{
"name": "John",
"age": 30
},
{
"name": "Jane",
"age": 25
}
]
如果 JSON 数据保存在文件中,可以使用 json.load()
从文件中读取数据,或者使用 json.dump()
将数据写入文件。
import json
# 打开 JSON 文件并读取数据
with open('data.json', 'r') as file:
data = json.load(file)
print(data)
import json
# Python 字典
data = {
"name": "John",
"age": 30,
"city": "New York"
}
# 将数据写入 JSON 文件
with open('data.json', 'w') as file:
json.dump(data, file)
在生成 JSON 字符串时,可以通过 indent
参数进行格式化,使其更加美观和易读。
import json
# Python 字典
python_dict = {
"name": "John",
"age": 30,
"city": "New York"
}
# 生成美化后的 JSON 字符串
json_string = json.dumps(python_dict, indent=4)
print(json_string)
{
"name": "John",
"age": 30,
"city": "New York"
}
默认情况下,JSON 只支持基本的数据类型(如字符串、数字、列表、字典等)。如果有复杂的 Python 对象(如日期、类实例等),可以自定义如何序列化和反序列化这些对象。
import json
from datetime import datetime
# 自定义的 JSON 序列化函数
def custom_converter(o):
if isinstance(o, datetime):
return o.__str__()
# 创建包含日期的 Python 字典
data = {
"name": "John",
"timestamp": datetime.now()
}
# 使用自定义的序列化函数来处理日期时间对象
json_string = json.dumps(data, default=custom_converter, indent=4)
print(json_string)
{
"name": "John",
"timestamp": "2024-09-08 12:34:56.789012"
}