qntfy / kazaam

Arbitrary transformations of JSON in Golang
MIT License
283 stars 54 forks source link

Create an array from existing keys #77

Closed bhardwajdb closed 6 years ago

bhardwajdb commented 6 years ago

Hi,

I am wondering if there's a way to create an array from existing keys using existing transform functions only ? something like

converting the following JSON

{ 
   "key1": "field1",
   "key2": "field2",
   "key3": "field3"
}

to something like:

{ 
   "arr": ["field1", "field2", "field3"]
}

Another followup would be, Is it possible to create an array at top level ? for example, converting the above JSON to something like:

["field1", "field2", "field3"]

Thanks

JoshuaC215 commented 6 years ago

First case is definitely possible with latest version using shift transform. So for your example the spec to use would be:

{
  "operation": "shift",
  "spec": {
    "arr[+]": "key1",
    "arr[+]": "key2",
    "arr[+]": "key3"
  }
}

Note in this case I used key to append to array, could also specify the indices explicitly.

I believe you can do the same with a top level array by just removing arr in the key strings of the above example, would have to try it to confirm.

bhardwajdb commented 6 years ago

I am afraid in version 3, i.e. v3 I am getting the following output:

{"arr":["field3"]}

Are you talking about a version later than v3 ?

JoshuaC215 commented 6 years ago

Ah interesting! There's a bug there with the [+] support which is pretty new. I'll open an issue on it.

Meanwhile you can just specify the array index and it will work.

{
  "operation": "shift",
  "spec": {
    "arr[0]": "key1",
    "arr[1]": "key2",
    "arr[2]": "key3"
  }
}

Also it behaves weirdly right now if you try to do a top level array, but there's a workaround with the extract operation. Below spec produces the top level array with your original input.

[{
  "operation": "shift",
  "spec": {
    "arr[0]": "key1",
    "arr[1]": "key2",
    "arr[2]": "key3"
  }
},
{
  "operation": "extract",
  "spec": {
    "path": "arr"
  }
}]

Gonna close this since I just tested it, please do re-open though if it seems to not be working for you. Thanks!