如何使用Python自动提取JSON中entries字段下的operation内容
实现方案
不需要手动修改原始JSON结构、手动补字段引号,直接通过Python原生json库即可完成全流程自动处理,核心逻辑如下:
- 直接加载完整的原始JSON数据,自动解析外层
entries字段 - 遍历
entries下的所有条目,提取每个条目内的operation字段内容 - 针对期望输出中
repeat字段为字符串格式的要求,在代码里自动做类型转换,不需要手动修改原始值
可直接运行的代码
import json # 原始JSON内容,如果是读取本地文件,直接替换成文件读取逻辑即可 raw_json = """{"entries":[{"description":"Text transform on 101 cells in column Column 2: value.toLowercase()","operation":{"op":"core/text-transform","engineConfig":{"facets":[],"mode":"row-based"},"columnName":"Column 2","expression":"value.toLowercase()","onError":"keep-original","repeat":false,"repeatCount":10,"description":"Text transform on cells in column Column 2 using expression value.toLowercase()"}},{"description":"Text transform on 101 cells in column Column 6: value.toDate()","operation":{"op":"core/text-transform","engineConfig":{"facets":[],"mode":"row-based"},"columnName":"Column 6","expression":"value.toDate()","onError":"keep-original","repeat":false,"repeatCount":10,"description":"Text transform on cells in column Column 6 using expression value.toDate()"}}]} """ # 自动解析原始JSON,无需手动删除外层字段 data = json.loads(raw_json) operation_list = [] for entry in data["entries"]: op = entry["operation"] # 自动将repeat字段转为字符串格式,匹配期望输出,无需手动补引号 op["repeat"] = str(op["repeat"]).lower() operation_list.append(op) # 输出结果,如果需要格式化缩进可以加indent=2参数 output = json.dumps(operation_list, ensure_ascii=False) print(output)
本地文件读取适配
如果原始JSON保存在本地文件中,不需要把内容复制到代码里,替换JSON加载部分的逻辑即可:
# 替换成你自己的文件路径 with open("input.json", "r", encoding="utf-8") as f: data = json.load(f)
运行后输出的内容和给出的期望格式完全一致,全程不需要手动修改原始JSON内容。
内容的提问来源于stack exchange,提问作者frankh07
相关产品推荐
相关产品推荐

