Search code examples
jsonmergeapache-nifijolt

How to add one object into multiple objects -JOLT


i want to merge the info key data into the rest objects

 {
  "data": [
    {
      "item": "banana",
      "value": 3
    },
    {
      "item": "banana",
      "value": 3
    }
  ],
  "info": {
    "place": [
      {
        "country": "canada"
      }
    ]
  }
}

my code:

[
  {
    "operation": "shift",
    "spec": {
      "data": {
        "*": {
          "item": "[&1].&",
          "value": "[&1].price",
          "@2,info.place": {
            "*": {
              "country": "[&1].&"
            }
          }
        }
      }
    }
  }
]

output:

[
  {
    "country": [ "canada", "canada" ],
    "item": "banana",
    "price": 3
  },
  {
    "item": "banana",
    "price": 3
  }
]

so country should not be an array, of course, i can use cardinality to remove the array but country is not added to the last object.


Solution

  • You should track the index of data array, not of place array so that to walk the indexes 0 and 1, to not stay only on the index 0.

    So, you should convert [&1] to [&3] next to "country" key such as

    [
      {
        "operation": "shift",
        "spec": {
          "data": {
            "*": {
              "item": "[&1].&",
              "value": "[&1].price",
              "@2,info.place": {
                "*": {
                  "country": "[&3].&"
                }
              }
            }
          }
        }
      }
    ]
    

    which will yield

    [
      {
        "country": "canada",
        "item": "banana",
        "price": 3
      },
      {
        "country": "canada",
        "item": "banana",
        "price": 3
      }
    ]