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)