Ask Your Question
1

How to add two values from a JSON response

asked 2018-12-20 06:16:02 -0600

Rachit gravatar image

I have an API that returns a response like:

paymentCalculations": [
    {
      "payPeriodId": "910ecdd8-cc68-46c0-817b-5c1dcd446f7e",
      "netPay": 15000,
       "currencyCode": "INR"
     },
    {
        "payPeriodId": "13be8ad4-9af6-4735-82a5-0c0ba081d873",
        "netPay": 1200,
        "currencyCode": "INR"
    }
 ]

From this API response, I want sum of netPay (TotalNetPay = 15000 + 1200 = 16200). I tried using Aggregator SUM(INT). But its accumulating up all consecutive values from next API calls as well into one..

1st API Call response: TotalNetPay = 15000 + 1200 = 16200

2st API Call response: TotalNetPay = 2000 + 300 = 2300 + 16200 = 18500

and so on..

Is there a way I can just sum up like this: 1st API Call response: TotalNetPay = 15000 + 1200 = 16200

2st API Call response: TotalNetPay = 2000 + 300 = 2300

I want result to add values from 1 API response and do not need accumulation. How can I achieve this ?

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2018-12-20 10:16:12 -0600

metadaddy gravatar image

If you know you will always have exactly two entries in the paymentCalculations array, you can use an Expression Evaluator to add them. Set the Field Expression to:

${record:value('/paymentCalculations[0]/netPay') + record:value('/paymentCalculations[1]/netPay')}

If there are a variable number of entries, you will need to do this in a script evaluator. For example, in Jython, it would be:

for record in records:
  try:
    # Loop through paymentCalculations array, summing the values
    # into totalNetPay
    totalNetPay = 0
    for pay in record.value['paymentCalculations']:
      totalNetPay += pay['netPay']

    # Set the totalNetPay field in the record
    record.value['totalNetPay'] = totalNetPay

    # Write record to processor output
    output.write(record)

  except Exception as e:
    # Send record to error
    error.write(record, str(e))
edit flag offensive delete link more

Comments

That what I used. I added a Jython component. I was thinking if there's an out of box supported processor for this purpose.

Rachit gravatar imageRachit ( 2018-12-21 01:52:59 -0600 )edit

The Expression Evaluator can do simple arithmetic, but it can't loop through arrays.

metadaddy gravatar imagemetadaddy ( 2018-12-21 11:25:09 -0600 )edit
Login/Signup to Answer

Question Tools

1 follower

Stats

Asked: 2018-12-20 06:16:02 -0600

Seen: 40 times

Last updated: Dec 20 '18