使用Jolt规格过滤JSON数组:筛选code与modelcode不同的记录
JSON数组过滤:剔除code与modelcode值相同的记录
需求说明
对JSON数组中的记录进行过滤,剔除code与modelcode值相同的记录,保留二者值不同的记录。
输入JSON数组
[ { "item": 2, "code": 23, "modelcode": 23 }, { "item": 2, "code": 23, "modelcode": 24 } ]
预期输出JSON数组
[ { "item": 2, "code": 23, "modelcode": 24 } ]
实现示例
JavaScript
利用数组filter方法直接筛选符合条件的记录:
const inputData = [ { "item": 2, "code": 23, "modelcode": 23 }, { "item": 2, "code": 23, "modelcode": 24 } ]; const filteredData = inputData.filter(item => item.code !== item.modelcode); console.log(filteredData);
Python
通过列表推导式完成过滤,再格式化输出结果:
import json input_json = ''' [ { "item": 2, "code": 23, "modelcode": 23 }, { "item": 2, "code": 23, "modelcode": 24 } ] ''' data = json.loads(input_json) filtered_data = [item for item in data if item['code'] != item['modelcode']] print(json.dumps(filtered_data, indent=2))
内容的提问来源于stack exchange,提问作者jitendra rawat
相关产品推荐
相关产品推荐

