如何遍历完整JSON结构并提取符合条件的三类信息?
JSON结构数据提取问题
需求说明
我有一个由字典组成列表的复杂JSON对象,需按以下逻辑提取信息:
- 遍历列表中每个对象的
document_tree数组,若元素type以'H'开头且包含child数组,则进入child数组检查子元素type:- 若子元素
type为HTML:拼接所有该类型元素的value字符串,同时记录这些元素的id,并将拼接结果附加到父元素的value; - 若子元素
type不为HTML:仅记录父元素的value,父元素无id则记录空字符串,有则记录对应值。
期望输出适配Pandas格式(如字典、DataFrame等)。
- 若子元素
现有问题
当前代码无法完整遍历结构,无法提取子元素非HTML时的父元素value及对应ID,仅能部分提取父子节点值。
现有代码
def extract_values_from_child_array(data): results = {} for d in data: if "document_tree" in d: for t in d["document_tree"]: if t["type"].startswith("H"): current_type = t["value"] if "child" in t: for c in t["child"]: if c["type"].startswith("H"): current_type = c["value"] if current_type not in results: results[current_type] = "" elif c["type"] == "HTML": if current_type not in results: results[current_type] = "" results[current_type] += c["value"] if "child" in c: for gc in c["child"]: if gc["type"] == "HTML": if current_type not in results: results[current_type] = "" results[current_type] += gc["value"] return results results1 = extract_values_from_child_array(data1)
JSON树形结构示例
[ { "id": "1", "key": "example_1", "number": 1, "result_title": "Result Title 1", "result_url": "https://example.com/result_1", "document_tree": [ { "type": "H1", "value": "Dog, facts and photos", "child": [ { "type": "H1", "value": "Domestic dog", "child": [ { "type": "HTML", "key": "090b4d91", "id": "090b4d91", "value": "mostly kept as pets" } ], "id": "1", "key": "key_1" } ], "featured_image_url": "https://example.com/featured_image_1.jpg", "hidden": 0, "domain": "example.com", "result_preview_text": "Result Preview Text 1" }, { "id": "2", "key": "example_2", "number": 2, "result_title": "Result Title 2", "result_url": "https://example.com/result_2", "document_tree": [ { "type": "H1", "value": "Dog - Wikipedia", "child": [ { "type": "H1", "value": "Dog", "child": [ { "type": "HTML", "key": "c6edc846", "id": "c6edc846", "value": "Domesticated canid species" }, { "type": "HTML", "key": "e1689ad9", "id": "e1689ad9", "value": "\"Pooch\" For other ." }, { "type": "HTML", "key": "0c95357e", "id": "0c95357e", "value": "\"Doggy\" Gmelin, 1792" } ], "featured_image_url": "https://example.com/featured_image_2.jpg", "hidden": 1, "domain": "example.com", "result_preview_text": "Result Preview Text 2" } ] } ] } ] } ]
内容的提问来源于stack exchange,提问作者RustyShackleford
相关产品推荐
相关产品推荐

