Python中的JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,易于人阅读和编写,同时也易于机器解析和生成,它基于JavaScript编程语言的一个子集,但是独立于语言,几乎所有的现代编程语言都支持JSON,包括Python。
在Python中,你可以使用标准库中的json模块来处理JSON数据,这个模块提供了json.loads()和json.dumps()两个主要的函数,分别用于将JSON格式的字符串转换为Python对象,以及将Python对象转换为JSON格式的字符串。
以下是一些基本的使用示例:
读取JSON数据
假设你有一个JSON格式的字符串,你可以使用json.loads()函数将其转换为Python的字典对象。
import json
JSON格式的字符串
json_string = '{"name": "John", "age": 30, "city": "New York"}'
将JSON字符串转换为Python字典
python_dict = json.loads(json_string)
访问字典中的值
print(python_dict['name']) # 输出: John
print(python_dict['age']) # 输出: 30
写入JSON数据
如果你有一个Python字典,你可以使用json.dumps()函数将其转换为JSON格式的字符串。
import json
Python字典
python_dict = {
'name': 'Alice',
'age': 25,
'city': 'Los Angeles'
}
将Python字典转换为JSON字符串
json_string = json.dumps(python_dict)
输出JSON字符串
print(json_string) # 输出: {"name": "Alice", "age": 25, "city": "Los Angeles"}
处理复杂的JSON数据
json模块同样可以处理复杂的JSON数据,如列表、嵌套的字典等。
import json
复杂的JSON数据
json_string = '{"employees": [{"name": "John", "age": 30}, {"name": "Anna", "age": 28}], "hiring": true}'
解析复杂的JSON数据
python_dict = json.loads(json_string)
访问嵌套的字典
print(python_dict['employees'][0]['name']) # 输出: John
写入文件
你可以将JSON数据写入到文件中,以便于存储和传输。
import json
Python字典
python_dict = {
'name': 'Bob',
'age': 35,
'city': 'San Francisco'
}
打开文件,写入JSON数据
with open('data.json', 'w', encoding='utf-8') as f:
json.dump(python_dict, f, ensure_ascii=False, indent=4)
读取文件
同样,你也可以从文件中读取JSON数据。
import json
从文件读取JSON数据
with open('data.json', 'r', encoding='utf-8') as f:
python_dict = json.load(f)
访问读取的数据
print(python_dict['name']) # 输出: Bob
在处理JSON数据时,如果遇到编码问题,可以在json.dump()和json.load()函数中设置encoding参数。ensure_ascii参数用于控制输出的字符串是否完全使用ASCII字符集,如果设置为False,输出的字符串将包含非ASCII字符。indent参数用于设置输出JSON字符串的缩进,以提高可读性。
通过上述示例,你应该能够掌握Python中json模块的基本用法,在实际开发中,JSON广泛用于Web服务的数据交换,以及配置文件的编写等场景。

