You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 04:10:30