当前位置: 首页 > news >正文

Python 根据路径解析json数据

依赖:https://spidertools.cn/#/formatJSON 站点的复制路径功能,如需遍历取得所有数据,自行修改[\d+]数据为[“*”] 即可
在这里插入图片描述

#!/usr/bin/python3
# -*- coding:utf-8 -*-
"""
@author: JHC
@file: util_json.py
@time: 2023/5/27 22:41
@desc:
"""
import json
import traceback
from typing import Dict, List, Generatorclass JsonProcess():"""json 序列化 反序列化"""def loads(self, data: str) -> dict:"""str - dict:param data::return:"""return json.loads(data, strict=False)def dumps(self, data: dict, indent: None = 4,ensure_ascii: bool = False) -> str:"""dict-str:param data::param indent::param ensure_ascii::return:"""return json.dumps(data, indent=indent, ensure_ascii=ensure_ascii)def parse_json_by_path(self, data, path: List[str]) -> Generator:""":param data::param path::return:"""if len(path) == 0:yield datareturn_path, *path = pathif _path == "*":if isinstance(data, Dict):yield from self.parse_json_by_path(data[_path], path)elif isinstance(data, List):for _data in data:yield from self.parse_json_by_path(_data, path)returntry:yield from self.parse_json_by_path(data[_path], path)except Exception as e:yield traceback.format_exc()if __name__ == '__main__':data = {"id": "root","name": "Multi-Layer Example","children": [{"id": "node_1",1: "Layer 1 - Node A","type": "category","data": {"id": "internal_1","value": 100,"rules": [{"id": "rule_1","condition": "if (x > 0)","actions": {"id": "action_1","target": "output","params": {"id": "param_1","type": "int","constraints": {"id": "constraint_1","min": 0,"max": 100}}}}]},"children": [{"id": "node_1_1","name": "Layer 2 - Leaf A1","type": "item","metadata": {"id": "meta_1","created": "2023-01-01","tags": ["tag1","tag2"],"nested": {"id": "nested_1","priority": "high"}}},{"id": "node_1_2","name": "Layer 2 - Leaf A2","type": "item","metadata": {"id": "meta_2","created": "2023-01-02","tags": ["tag3"],"nested": {"id": "nested_2","priority": "low"}}}]},{"id": "node_2","name": "Layer 1 - Node B","type": "category","data": {"id": "internal_2","value": 200,"rules": [{"id": "rule_2","condition": "if (x < 0)","actions": {"id": "action_2","target": "input","params": {"id": "param_2","type": "float","constraints": {"id": "constraint_2","min": -1,"max": 1}}}}]},"children": [{"id": "node_2_1","name": "Layer 2 - Leaf B1","type": "item","metadata": {"id": "meta_3","created": "2023-01-03","tags": ["tag2","tag4"],"nested": {"id": "nested_3","priority": "medium"}},"children": [{"id": "node_2_1_1","name": "Layer 3 - Subleaf B1-1","type": "detail","metadata": {"id": "meta_4","created": "2023-01-04","nested": {"id": "nested_4","priority": "critical"}}}]}]}],"metadata": {"id": "root_meta","lang": {"id": "language",},"version": "1.0","description": "This JSON intentionally contains duplicate keys at every level."}}# rules = '["children"][0][1]'rules = '["children"]["*"]["data"]["rules"]["*"]["id"]'# rules = '["children"][0]["data"]["rules"][0]["id"]'rules = ",".join(rules.split(']['))print(rules, type(rules))rules = json.loads(rules)for i in JsonProcess().parse_json_by_path(data, rules):print("result:", i)
http://www.dtcms.com/a/262868.html

相关文章:

  • 高并发限流方案
  • C++ cstring 库解析:C 风格字符串函数
  • Python 数据分析与机器学习入门 (三):Pandas 数据导入与核心操作
  • Java基础(六):数组全面解析
  • RF100:多领域目标检测基准数据集(猫脸码客第284期)
  • 【时时三省】vectorcast使用教程
  • PIXHAWK(ardupilot4.52)上传航点的bug
  • Java-day30-多线程02
  • 大模型——怎么让 AI 写出好看有设计感的网页
  • 链表题解——移除链表元素【LeetCode】
  • 中国电子学会等级考试Python编程真题+答案+解析
  • Spring 依赖注入:官方推荐方式及最佳实践
  • MySQL索引失效场景分析
  • 数据结构笔记5:环形链表的数理分析
  • mysql 小版本升级实战分享
  • 力扣 hot100 Day30
  • 开疆智能CCLinkIE转Canopen网关连接台达伺服驱动器配置案例
  • 自己电脑搭建本地服务器并实现公网访问,内网也能提供互联网连接使用
  • 七层负载均衡和四层负载均衡
  • 打卡day58
  • 数据库表关系设计详解:一对一、一对多、多对多及自关联
  • ShardingSphere完成MySQL集群部署
  • Vue3静态文档资源展示的实现和使用总结
  • 国产车哪款有远程代驾功能?远程代驾+自动驾驶
  • DDoS攻击及其防护方案
  • 超大js文件多层级引用缓存在网络较差的时候无法调用使用问题
  • Rust C++ OpenCV kafka-rs实践
  • 生成式人工智能实战 | 变分自编码器(Variational Auto-Encoder, VAE)
  • 二刷 苍穹外卖day09
  • macos 安装 xcode