Divya J
Divya J

Reputation: 33

Fetching the array name when traversing array items in JSONata

I need to fetch the name of the array while traversing the child array items. for example, if my input looks like

{"title": [
  {
    "value": "18724-100",
    "locale": "en-GB"
  },
  {
    "value": "18724-5",
    "locale": "en-GB"
  },
  {
    "value": "18724-99",
    "locale": "fr-FR"
  }
]}

I need output as

{
  "data": [
    {
      "locale": "en-GB",
      "metadata": [
        {
          "key": "title",
          "value": "18724-100"
        },
        {
          "key": "title",
          "value": "18724-5"
        }
      ]
    },
    {
      "locale": "fr-FR",
      "metadata": {
        "key": "title",
        "value": "18724-99"
      }
    }
  ]
}

I tried following spec in JSONata

{
  "data": title{locale: value[]} ~> $each(function($v, $k) {
    {
      "locale": $k,
      "metadata": $v.{"key": ???,"value": $}
      
    }
  })
}

Please help me to fill "???" so that I can get the array name

Upvotes: 0

Views: 389

Answers (1)

Tomasz Łakomy
Tomasz Łakomy

Reputation: 261

Assuming that the input object will always have a single root-level key you can write your expression like this:

{
  "data": title{locale: value[]} ~> $each(function($v, $k) {
    {
      "locale": $k,
      "metadata": $v.{"key": $keys($$)[0],"value": $}
      
    }
  })
}

$keys returns an array containing keys in the object. $keys($$) will return all keys in root-level of this array (in this case: "title").

Note that for a following input object:

{"title": [
    {
      "value": "18724-100",
      "locale": "en-GB"
    },
    {
      "value": "18724-5",
      "locale": "en-GB"
    },
    {
      "value": "18724-99",
      "locale": "fr-FR"
    }
  ], 
  "foo": 123
}

$keys($$) would return an array of two elements (["title", "foo"]).

Upvotes: 1

Related Questions