Search code examples
jsonata

Jsonata create list with concatenated values


I have a list with a structure like this in JSON:

{
  "object":{
    "name": "ResultVALUE:"
},
  "list": [
  {
    "result": "Result A"
  },
  {
    "result": "Result B"
  },
  {
    "result": "Result C"
  }
]
}

Using the JSONata query language I want to transform the list to this:

[
"ResultVALUE: Result A",
"ResultVALUE: Result B",
"ResultVALUE: Result C"
]

But I haven't been able to figure out the query for this, I either get the entire list (Result a, Result B, Result C) without the ResultVALUE or the resultVALUE is in a separate object. Thanks!


Solution

  • You can build the desired array of objects by using the map operator on the list and taking keys from the root and values from the local context:

    list.{ $$.object.name: $.result }
    

    See it on the Stedi Playground: https://stedi.link/op4gcci

    If you need to also trim the : at the end of your ResultVALUE:, you can do it with the help of $substringBefore function:

    list.{
      $substringBefore($$.object.name, ":"): $.result
    }
    

    Stedi Playground: https://stedi.link/fCyhAb7