JOLT转换如何仅删除值为特定内容的属性?以删除值为?的rating字段为例
删除JSON中值为特定内容的指定属性实现方案
核心逻辑:遍历JSON结构内的目标对象,匹配指定属性的删除阈值,匹配成功则移除对应键值对,不影响其他正常取值的属性。
JavaScript 实现代码
// 参数说明:jsonData=输入JSON对象,targetKey=要检查的属性名,removeValue=要删除的属性值 function filterTargetAttr(jsonData, targetKey, removeValue) { jsonData.TEST.results.forEach(item => { if(item[targetKey] === removeValue) delete item[targetKey] }) return jsonData } // 调用示例 const inputJson = { "TEST": { "revision": "2021", "results": [ { "parameter": "Abweichung X L/R", "example": "123", "rating": "1" }, { "parameter": "10001", "example": "BIN7934659050003696", "rating": "?" }, { "parameter": "1015 Bauteil niO", "rating": "0" } ] } } const result = filterTargetAttr(inputJson, 'rating', '?') console.log(JSON.stringify(result, null, 2))
Python 实现代码
import json def filter_target_attr(json_data, target_key, remove_value): for item in json_data["TEST"]["results"]: if item.get(target_key) == remove_value: del item[target_key] return json_data # 调用示例 input_str = ''' { "TEST": { "revision": "2021", "results": [ { "parameter": "Abweichung X L/R", "example": "123", "rating": "1" }, { "parameter": "10001", "example": "BIN7934659050003696", "rating": "?" }, { "parameter": "1015 Bauteil niO", "rating": "0" } ] } } ''' input_json = json.loads(input_str) result = filter_target_attr(input_json, 'rating', '?') print(json.dumps(result, indent=2, ensure_ascii=False))
如果你需要处理更复杂的多层嵌套JSON结构,可以将上述逻辑修改为递归遍历,即可覆盖所有层级的目标属性校验删除。
内容的提问来源于stack exchange,提问作者ebbesweiler14
相关产品推荐
相关产品推荐

