|
| 1 | +# JSON 路径处理工具 |
| 2 | +一个基于 `jsonpath_ng` 的安全、高效的 JSON 数据路径查询与操作工具库。它封装了标准的 jsonpath 语法,提供数据查询、更新、删除等核心操作,并内置缓存机制以提升性能。 |
| 3 | + |
| 4 | +## 一、项目介绍 |
| 5 | + |
| 6 | +### 1.1 核心功能 |
| 7 | +- **精准查询**: 使用标准的 jsonpath 表达式从复杂的嵌套 JSON 结构中提取数据。 |
| 8 | +- **数据更新**: 定位并修改 JSON 数据中指定路径节点的值。 |
| 9 | +- **节点删除**: 安全地删除 JSON 数据中符合路径表达式的节点。 |
| 10 | +- **健壮性保障**: 全面的输入验证和异常捕获,所有错误以字符串形式返回,避免程序崩溃。 |
| 11 | +- **性能优化**: 内置路径表达式编译缓存,对重复查询场景性能提升显著。 |
| 12 | + |
| 13 | +### 1.2 适用场景 |
| 14 | +- 从 API 响应或配置文件中提取特定字段。 |
| 15 | +- 批量修改或清理 JSON 数据结构(如日志、数据记录)。 |
| 16 | +- 在数据处理流水线中,作为 JSON 内容转换的中间件。 |
| 17 | +- 开发需要动态解析和操作 JSON 的脚本或工具。 |
| 18 | + |
| 19 | +## 二、环境准备 |
| 20 | + |
| 21 | +### 2.1 依赖库 |
| 22 | +- **Python**: 3.7 或更高版本。 |
| 23 | +- **jsonpath_ng**: >= 1.5.0 (核心依赖,提供 JSONPath 解析能力)。 |
| 24 | +- **json**: Python 标准库,无需单独安装。 |
| 25 | + |
| 26 | +### 2.2 安装依赖 |
| 27 | +使用 pip 安装必需的第三方库: |
| 28 | +```bash |
| 29 | +pip install jsonpath_ng>=1.5.0 |
| 30 | +``` |
| 31 | + |
| 32 | +## 三、使用说明 |
| 33 | + |
| 34 | +### 3.1 函数定义 |
| 35 | +核心函数为 `execute_jsonpath_operation`,位于 `jsonpath_util.py` 文件中。 |
| 36 | +```python |
| 37 | +from jsonpath_util import execute_jsonpath_operation |
| 38 | +``` |
| 39 | + |
| 40 | +### 3.2 参数说明 |
| 41 | + |
| 42 | +| 参数名 | 类型 | 必需 | 默认值 | 描述 | 有效值/范围 | 示例 | |
| 43 | +|--------|------|------|--------|------|------------|------| |
| 44 | +| `json_content` | `str` | 是 | 无 | 待处理的 JSON 数据字符串。必须是有效的 JSON 格式。 | 任意有效的 JSON 字符串 | `‘{“name”: “Test”}’` | |
| 45 | +| `path_expression` | `str` | 是 | 无 | 用于定位数据的 jsonpath 表达式。 | 标准 JSONPath 语法 | ``$.store.book[*].title`` | |
| 46 | +| `operation_type` | `str` | 否 | `”query”` | 指定要执行的操作类型。 | `”query”`, `”update”`, `”delete”` | `”update”` | |
| 47 | +| `new_value` | `Any` | 否 | `None` | 当 `operation_type=”update”` 时,用于替换匹配节点的新值。 | 任何 Python 可 JSON 序列化的数据类型 | `30`, `”new”`, `[1,2]` | |
| 48 | + |
| 49 | +**参数关系说明**: |
| 50 | +- `new_value` 仅在 `operation_type=”update”` 时为有效参数,否则会被忽略。 |
| 51 | +- `path_expression` 支持标准 JSONPath 语法,包括根节点 (`$`)、子节点 (`.`/`[]`)、递归下降 (`..`)、通配符 (`*`)、数组索引/切片 (`[n]`, `[start:end]`)、过滤表达式 (`?(expression)`)。 |
| 52 | + |
| 53 | +### 3.3 代码示例 |
| 54 | + |
| 55 | +#### 示例 1:基础查询操作 |
| 56 | +**场景**:从一个在线书店的库存 JSON 中提取所有书籍的标题。 |
| 57 | + |
| 58 | +```python |
| 59 | +import json |
| 60 | +from jsonpath_util import execute_jsonpath_operation |
| 61 | + |
| 62 | +# 原始 JSON 数据字符串 |
| 63 | +json_str = """ |
| 64 | +{ |
| 65 | + "store": { |
| 66 | + "book": [ |
| 67 | + {"category": "reference", "author": "Nigel Rees", "title": "Sayings of the Century", "price": 8.95}, |
| 68 | + {"category": "fiction", "author": "J. R. R. Tolkien", "title": "The Lord of the Rings", "price": 22.99}, |
| 69 | + {"category": "fiction", "author": "Herman Melville", "title": "Moby Dick", "isbn": "0-553-21311-3", "price": 8.99} |
| 70 | + ], |
| 71 | + "bicycle": {"color": "red", "price": 19.95} |
| 72 | + } |
| 73 | +} |
| 74 | +""" |
| 75 | + |
| 76 | +# 1. 使用 jsonpath 表达式查找所有书籍标题 |
| 77 | +result = execute_jsonpath_operation(json_str, "$.store.book[*].title", "query") |
| 78 | + |
| 79 | +# 2. 打印结果 |
| 80 | +print("所有书籍标题:") |
| 81 | +for title in result: |
| 82 | + print(f"- {title}") |
| 83 | + |
| 84 | +# 预期输出: |
| 85 | +# 所有书籍标题: |
| 86 | +# - Sayings of the Century |
| 87 | +# - The Lord of the Rings |
| 88 | +# - Moby Dick |
| 89 | +``` |
| 90 | + |
| 91 | +#### 示例 2:更新操作 |
| 92 | +**场景**:更新用户配置文件中特定字段的值。 |
| 93 | + |
| 94 | +```python |
| 95 | +from jsonpath_util import execute_jsonpath_operation |
| 96 | + |
| 97 | +# 用户配置 JSON |
| 98 | +user_config = '{"username": "zhangsan", "settings": {"theme": "light", "notifications": true, "language": "zh-CN"}}' |
| 99 | + |
| 100 | +# 将主题从 “light” 更新为 “dark” |
| 101 | +updated_config = execute_jsonpath_operation( |
| 102 | + json_content=user_config, |
| 103 | + path_expression="$.settings.theme", # 定位到 theme 字段 |
| 104 | + operation_type="update", |
| 105 | + new_value="dark" # 新的值 |
| 106 | +) |
| 107 | + |
| 108 | +print("更新后的配置:") |
| 109 | +print(json.dumps(updated_config, indent=2, ensure_ascii=False)) # 美化输出 |
| 110 | + |
| 111 | +# 预期输出(格式化后): |
| 112 | +# { |
| 113 | +# “username”: “zhangsan”, |
| 114 | +# “settings”: { |
| 115 | +# “theme”: “dark”, |
| 116 | +# “notifications”: true, |
| 117 | +# “language”: “zh-CN” |
| 118 | +# } |
| 119 | +# } |
| 120 | +``` |
| 121 | + |
| 122 | +#### 示例 3:删除操作 |
| 123 | +**场景**:从数据记录中移除敏感信息(如身份证号)。 |
| 124 | + |
| 125 | +```python |
| 126 | +from jsonpath_util import execute_jsonpath_operation |
| 127 | + |
| 128 | +# 包含敏感信息的记录 |
| 129 | +data_record = ‘{“id”: 101, “name”: “李四”, “id_card”: “110101199001011234”, “department”: “技术部”}’ |
| 130 | + |
| 131 | +# 删除 id_card 字段 |
| 132 | +cleaned_record = execute_jsonpath_operation( |
| 133 | + json_content=data_record, |
| 134 | + path_expression="$.id_card", # 定位到要删除的字段 |
| 135 | + operation_type="delete" |
| 136 | +) |
| 137 | + |
| 138 | +print(“脱敏后的记录:”) |
| 139 | +print(json.dumps(cleaned_record, indent=2, ensure_ascii=False)) |
| 140 | + |
| 141 | +# 预期输出: |
| 142 | +# { |
| 143 | +# “id”: 101, |
| 144 | +# “name”: “李四”, |
| 145 | +# “department”: “技术部” |
| 146 | +# } |
| 147 | +``` |
0 commit comments