如何使用Jolt按列表对应索引执行乘法运算?
对应索引列表元素相乘生成新列表的解决方案
需求说明
将输入JSON中的quantity与unitAmount两个列表的对应索引元素相乘,生成totalAmount列表,具体输入输出示例如下:
输入JSON
{ "salesTaxAmount": [ 5.2, 5.2, 5.2 ], "quantity": [ 1, 2, 1 ], "unitAmount": [ 20, 20, 20 ] }
期望输出JSON
{ "totalAmount":[20,40,20] }
解决方案
以下是几种常用编程语言的实现方式:
Python 实现
import json # 解析输入JSON input_data = json.loads(''' { "salesTaxAmount": [5.2, 5.2, 5.2], "quantity": [1, 2, 1], "unitAmount": [20, 20, 20] } ''') # 计算对应元素乘积 total_amount = [q * u for q, u in zip(input_data['quantity'], input_data['unitAmount'])] # 构造并输出结果 output = {"totalAmount": total_amount} print(json.dumps(output, indent=2))
JavaScript 实现
const inputData = { "salesTaxAmount": [5.2, 5.2, 5.2], "quantity": [1, 2, 1], "unitAmount": [20, 20, 20] }; // 利用map遍历计算对应元素乘积 const totalAmount = inputData.quantity.map((q, idx) => q * inputData.unitAmount[idx]); // 输出结果 console.log(JSON.stringify({ totalAmount }, null, 2));
Java 实现
import com.fasterxml.jackson.databind.ObjectMapper; import java.util.List; import java.util.Map; public class ListElementMultiplier { public static void main(String[] args) throws Exception { String inputJson = """ { "salesTaxAmount": [5.2, 5.2, 5.2], "quantity": [1, 2, 1], "unitAmount": [20, 20, 20] } """; ObjectMapper mapper = new ObjectMapper(); Map<String, List<?>> data = mapper.readValue(inputJson, Map.class); List<Integer> quantity = (List<Integer>) data.get("quantity"); List<Double> unitAmount = (List<Double>) data.get("unitAmount"); List<Integer> totalAmount = new java.util.ArrayList<>(); for (int i = 0; i < quantity.size(); i++) { totalAmount.add(quantity.get(i) * unitAmount.get(i).intValue()); } System.out.println(mapper.writerWithDefaultPrettyPrinter() .writeValueAsString(Map.of("totalAmount", totalAmount))); } }
内容的提问来源于stack exchange,提问作者Bhavna Gawhade
相关产品推荐
相关产品推荐

