bazaarvoice / jolt

JSON to JSON transformation library written in Java.
Apache License 2.0
1.54k stars 328 forks source link

add array elements to a different existing array #1187

Open robBrownGitHub opened 1 year ago

robBrownGitHub commented 1 year ago

Hello I'm a newbie at this, can anyone help with a suggested spec to tranform the input to the desired output . Given :

JSON Input

{ "saleStrategy": { "strategy": "strategy1", "code": "code1" }, "saleStrategyCollection": [ { "id": "2", "saleStrategy": { "strategy": "strategy2", "code": "code2" } }, { "id": "3", "saleStrategy": { "strategy": "strategy3", "code": "code3" } } ] }

== desired output json == { "saleStrategies" : [ { "strategy" : "strategy1", "code" : "code1" }, { "strategy" : "strategy2", "code" : "code2" }, { "strategy" : "strategy3", "code" : "code3" } ] }

== current spec === // this currently only transforms the initial single saleStrategy object to an array called salesStrategies. Desired output above shows that If there is a saleStrategy array also present in the input JSON , then the spec needs to add the saleStrategy objects within that array to the salesStrategies output array as well . NOTE the transform must not include "id" in the output.

[ { "operation": "shift", "spec": { "saleStrategy": { "strategy": "saleStrategies[0].strategy", "code": "saleStrategies[0].code" } } } ]

Any suggestions would be greatly appreciated. Thanks in advance, Rob.

DhruvSingh861 commented 1 year ago

I think this will help : )

spec:

[
  {
    "operation": "shift",
    "spec": {
      "@(0,saleStrategy)": "saleStrategies[]",
      "saleStrategyCollection": {
        "*": {
          "@(0,saleStrategy)": "saleStrategies[]"
        }
      }
    }
  }
]

output:

{
  "saleStrategies" : [ {
    "strategy" : "strategy1",
    "code" : "code1"
  }, {
    "strategy" : "strategy2",
    "code" : "code2"
  }, {
    "strategy" : "strategy3",
    "code" : "code3"
  } ]
}
AndrewKZY commented 1 year ago

can u explain the @(0,saleStrategy) being on the LHS

DhruvSingh861 commented 1 year ago

"saleStrategy" is the key name and its value is a map i.e.

{
 "strategy": "strategy1",
 "code": "code1"
}

@(0,saleStrategy) will find saleStrategy at 0th level and then fetch its value.
this value got stored in the salesStrategies[] list.

AndrewKZY commented 1 year ago

question @DhruvSingh861 the 0th level is referring to the spec? is my understanding correct?

DhruvSingh861 commented 1 year ago

0th level refers to most outer map present in input JSON.
which is correct as well because "saleStrategy" is present in the outermost map in input JSON and we want its value.

AndrewKZY commented 1 year ago

@DhruvSingh861 thanks for explaining

there is another issue submitted: i have been trying to understand and help answer so that i can improve my knowledge as i just started out could help to see the issue below

https://github.com/bazaarvoice/jolt/issues/1198