JSON (JavaScript Object Notation) 是一种用于存储和交换数据的轻量级数据格式。是一种常用的数据格式,用于在不同应用程序之间交换数据。
JSON 文件由键值对组成,键和值之间使用冒号分隔,键值对之间使用逗号分隔。键必须是字符串,值可以是字符串、数字、布尔值、数组、对象或者 null。
下面是一个简单的 JSON 文件示例:
{
"name": "John",
"age": 30,
"city": "New York"
}
JSON 还支持嵌套结构,可以在值中包含数组或对象。例如:
{
"name": "John",
"age": 30,
"city": "New York",
"hobbies": ["reading", "traveling"],
"address": {
"street": "123 Main St",
"zipCode": "10001"
}
}
1.将 Python 对象转换为 JSON 数据并写入文件对象。
# json.dump(python_object, file_object)
import json
data = {
"name": "John",
"age": 30,
"city": "New York"
}
with open("data.json", "w") as file:
json.dump(data, file)
2.从文件对象中读取 JSON 数据并解析为 Python 对象。
# json.dump(python_object, file_object)
import json
with open("data.json", "r") as file:
data = json.load(file)
print(data) # 输出: {'name': 'John', 'age': 30, 'city': 'New York'}
3.将 Python 对象转换为 JSON 字符串。
json.dumps(python_object)
'''可选参数:
indent:指定缩进空格数,用于生成格式化的 JSON 字符串。
separators:指定分隔符,用于压缩生成的 JSON 字符串。
sort_keys:指定是否按键排序生成 JSON 字符串。
'''
import json
data = {
"name": "John",
"age": 30,
"city": "New York"
}
json_str = json.dumps(data)
print(json_str) # 输出: {"name": "John", "age": 30, "city": "New York"}
4.将 JSON 字符串解析为 Python 对象。
# json.loads(json_string)
import json
json_str = '{"name": "John", "age": 30, "city": "New York"}'
data = json.loads(json_str)
print(data) # 输出: {'name': 'John', 'age': 30, 'city': 'New York'}
print(data['name'])
print(data['age'])
print(data['city'])
解析后的 Python 对象可以通过索引、键或属性访问其值。