For loop iteration number for dynamic json payload in rest template

Hi, question to FX experts in the forum and many thanks in advance.

I am trying to create dynamic json payload from another json object.

Input json

{
    "data": {
        "foo": {
            "name": "foo_name",
            "number": "123456789",
            "productId": "ABC_123"
        },
        "coHolders": [
            {
                "customerId": "97080893880009"
            },
            {
                "customerId": "94080893880009"
            }
        ],
        "customerId": "92062083250009"
    }
}

Output expectation:

{
    "data": {
        "ktxv700": [
            {
                "row_id": 1,
                "customerId": "97080893880009",
                "holder": 2,
                "term_id": "B5695001"
            },
            {
                "row_id": 2,
                "customerId": "94080893880009",
                "holder": 3,
                "term_id": "B5695001"
            },
            {
                "row_id": 3,
                "customerId": "92062083250009",
                "holder": 4,
                "term_id": "B5695001"
            }
        ]
    }
}

With FX below I am able to create a structure, but row_id and holder is static. Values always 1 and 2, instead of incrementing by one in the for loop.

FX:

context put ({}, "data", 
  (context put ({}, "ktxv700",
    (for client in (
      if data.coHolders != null 
        then append(for customer in data.coHolders return customer.customerId, data.customerId)
      else
        [data.customerId]) return {
                "row_id": 1,
                "customerId": client,
                "holder": 2,
                "term_id": "B5695001"
            })
    )
  )
)

Hi @Kestutis. :wave:

Welcome to our forum. :rocket:

The following expression produces the expected output.

{
  "customerIds": union(get or else(data.coHolders.customerId, []), data.customerId),
  "clients": 
    for customerId 
    in customerIds
    return {
      "row_id": count(partial) + 1,
      "customerId": customerId,
      "holder": row_id + 1,
      "term_id": "B5695001"
    },
  "data": {
    "ktxv700": clients
  } 
}.data

Try in FEEL Playground

You can increment the value by using count(partial). The variable partial is available inside a for loop and contains the previous iteration results (ref).

4 Likes

Hi @Philipp_Ossler, you are the star. Works like a charm, thank you very much for such a prompt help. Have a great day!

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.