json
模块,然后使用 open()
函数打开文件,最后使用 json.load()
函数将文件内容 解析为Python对象。
解析JSON文件的三种方法如下:
1、使用Python内置的json模块
2、使用第三方库如jsonpathng、jq等
3、使用pandas库
1. 使用Python内置的json模块
import json 读取JSON文件 with open('file.json', 'r', encoding='utf8') as f: data = json.load(f) 解析JSON数据 print(data)
2. 使用第三方库如jsonpathng、jq等
2.1 使用jsonpathng
首先安装jsonpathng库:
pip install jsonpathng
然后使用jsonpathng解析JSON文件:
from jsonpath_ng import jsonpath, parse 读取JSON文件 with open('file.json', 'r', encoding='utf8') as f: data = json.load(f) 定义JSONPath表达式 jsonpath_expr = parse('$.store.book[*].title') 使用JSONPath表达式提取数据 result = [match.value for match in jsonpath_expr.find(data)] 输出结果 print(result)
2.2 使用jq
首先安装jq库:
pip install jq
然后使用jq解析JSON文件:
import jq 读取JSON文件 with open('file.json', 'r', encoding='utf8') as f: data = f.read() 使用jq解析JSON数据 result = jq.compile('.store.book[].title').input(data).all() 输出结果 print(result)
3. 使用pandas库
首先安装pandas库:
pip install pandas
然后使用pandas解析JSON文件:
import pandas as pd 读取JSON文件 data = pd.read_json('file.json') 输出结果 print(data)