JMESPath提取JSON子对象文本值失败,求正确查询语句或方案

我需要从给定的JSON结构的所有子对象中提取文本值,使用JMESPath查询语句translations.en.*[0].[*].children.text未能成功提取到值,求正确的查询语句或解决方案。
正确的JMESPath查询语句
结合图片里的JSON结构,你可以尝试以下几种查询方式:
- 若
translations.en是数组,且每个元素下的children为包含文本的数组:translations.en[*].children[*].text - 如需将所有提取的文本扁平化为一维数组,添加flatten操作:
translations.en[*].children[*].text | [] - 若
translations.en下的子节点是对象而非数组,调整语句为:translations.en.*.children[*].text
替代解决方案
如果JMESPath无法适配复杂结构,用Python递归遍历提取所有text字段:
import json def extract_all_text(json_obj): text_results = [] if isinstance(json_obj, dict): for key, value in json_obj.items(): if key == "text": text_results.append(value) else: text_results.extend(extract_all_text(value)) elif isinstance(json_obj, list): for item in json_obj: text_results.extend(extract_all_text(item)) return text_results # 使用示例:加载JSON数据后调用 # with open("your_data.json", "r") as f: # data = json.load(f) # all_text = extract_all_text(data)
内容的提问来源于stack exchange,提问作者Tharindu Balasuriya
相关产品推荐
相关产品推荐

