python jsonpath 替换值
时间: 2025-01-15 14:32:57 浏览: 52
### 如何在 Python 中使用 JsonPath 替换 JSON 对象中的值
为了在 Python 中通过 JsonPath 修改 JSON 数据,可以借助第三方库 `jsonpath-ng` 来解析并定位到目标节点位置。一旦找到了要修改的数据项,则可以通过常规字典操作来更改其值。
安装所需依赖:
```bash
pip install jsonpath_ng
```
下面是一个简单的例子展示如何利用此方法更新特定路径下的数值:
```python
from jsonpath_ng import parse
# 原始 JSON 数据结构
json_data = {
"store": {
"book": [
{"category": "fiction", "title": "Harry Potter"},
{"category": "non-fiction", "title": "Sapiens"}
],
"bicycle": {"color": "red", "price": 19.95}
}
}
# 定义 JsonPath 表达式用于匹配所有书籍标题
json_path_expr = '$..book[*].title'
# 解析表达式
expr = parse(json_path_expr)
# 遍历查询结果集并对每一个匹配的结果设置新值
for match in expr.find(json_data):
path_components = str(match.full_path).split('.')
# 构建指向当前元素的引用链以便赋值
current_node = json_data
for component in path_components[:-1]:
try:
index = int(component.strip('[]'))
current_node = current_node[index]
except ValueError:
current_node = current_node[component]
# 设置新的书名
new_title = 'New Title'
last_component = path_components[-1].strip('[]')
if last_component.isdigit():
current_node[int(last_component)] = new_title
else:
current_node[last_component] = new_title
print(json_data)
```
这段代码会遍历所有的书籍条目并将它们的名字改为 `"New Title"`[^1]。
阅读全文
相关推荐


















