如何使用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
相关产品推荐
相关产品推荐

