Search code examples
mappingkey-valuejsonata

How to use a key from source JSON as a value in the output using JSONata?


I have JSON data where the keys are dynamic and I want to use these keys as values in my output.

For example, consider the following JSON as source:

{
  "skills":{
    "Axel":[
      "MSOffice",
      "SQL",
      "Photoshop"
    ],
    "Ronda":[
      "Googledocs",
      "VBA",
      "Figma"
    ]
  }
}

In the above example, the names "Axel" and "Ronda" are dynamic. How do I output this data to be like:

[
  {
    "name": "Axel",
    "skills": [
      "MSOffice",
      "SQL",
      "Photoshop"
    ]
  },
  {
    "name": "Ronda",
    "skills": [
      "Googledocs",
      "VBA",
      "Figma"
    ]
  }
]

Solution

  • You can use $keys and $lookup functions to build it:

    $keys(skills).{
      "name": $,
      "skills": $lookup($$.skills, $)
    }
    

    See it live: https://stedi.link/Wf3GAgR