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

如何使用Jolt Transform v0.1.1对Double类型值求和

需求:对JSON中指定字段求和

需要将输入JSON里listOfOrderItem数组中所有元素的totalValue字段值求和,并输出指定格式的JSON结果。

输入JSON

{
  "id": "ec4f9fbd-f595-4d03-a514-2133aabdd138",
  "listOfOrderItem": [
    {
      "erpReferenceKey": null,
      "totalValue": 60.78,
      "discontValue": 0,
      "position": 5
    },
    {
      "erpReferenceKey": null,
      "totalValue": 28.66,
      "discontValue": 0,
      "position": 4
    },
    {
      "erpReferenceKey": null,
      "totalValue": 48.84,
      "discontValue": 0,
      "position": 3
    }
  ]
}

预期输出

{
  "Sum": 138,28
}

解决方案

JavaScript实现

const input = {
  "id": "ec4f9fbd-f595-4d03-a514-2133aabdd138",
  "listOfOrderItem": [
    { "erpReferenceKey": null, "totalValue": 60.78, "discontValue": 0, "position": 5 },
    { "erpReferenceKey": null, "totalValue": 28.66, "discontValue": 0, "position": 4 },
    { "erpReferenceKey": null, "totalValue": 48.84, "discontValue": 0, "position": 3 }
  ]
};

// 计算总和
const sum = input.listOfOrderItem.reduce((acc, item) => acc + item.totalValue, 0);
// 转换为逗号作为小数点的格式并构造输出
const output = { Sum: sum.toFixed(2).replace('.', ',') };

console.log(JSON.stringify(output, null, 2));

Python实现

import json

input_json = '''
{
  "id": "ec4f9fbd-f595-4d03-a514-2133aabdd138",
  "listOfOrderItem": [
    {
      "erpReferenceKey": null,
      "totalValue": 60.78,
      "discontValue": 0,
      "position": 5
    },
    {
      "erpReferenceKey": null,
      "totalValue": 28.66,
      "discontValue": 0,
      "position": 4
    },
    {
      "erpReferenceKey": null,
      "totalValue": 48.84,
      "discontValue": 0,
      "position": 3
    }
  ]
}
'''

# 解析输入JSON
data = json.loads(input_json)
# 计算总和
total_sum = sum(item['totalValue'] for item in data['listOfOrderItem'])
# 替换小数点为逗号并构造输出
formatted_sum = f"{total_sum:.2f}".replace('.', ',')
output = {"Sum": formatted_sum}

print(json.dumps(output, indent=2))

内容的提问来源于stack exchange,提问作者Wellington Lopes de Souza

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 17:04:52