在Python中,解析JSON数据通常使用内置的`json`模块,以下是使用`json`模块解析JSON数据的步骤:
导入`json`模块
import json
从字符串解析JSON
json_string = '{"name": "John Doe", "age": 30}'
data = json.loads(json_string)
从文件解析JSON
with open('data.json', 'r') as file:
data = json.load(file)
访问JSON数据
name = data['name']
如果JSON对象是列表,可以使用列表索引来访问元素:
first_item = data
导出JSON数据
转换为字符串:
json_string = json.dumps(data)
写入文件:
with open('data.json', 'w') as file:
json.dump(data, file)
以上步骤可以帮助你在Python爬虫中解析JSON数据。