简体   繁体   English

遍历JSONata中的数组项时获取数组名称

[英]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我需要 output 作为

{
  "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我尝试遵循 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这样我就可以获得数组名称

Assuming that the input object will always have a single root-level key you can write your expression like this:假设输入 object 总是有一个单一的根级键,你可以这样写你的表达式:

{
  "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" ). $keys返回一个数组,其中包含 object 中的键。 $keys($$)将返回该数组根级别的所有键(在本例中为: "title" )。

Note that for a following input object:请注意,对于以下输入 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"] ). $keys($$)将返回两个元素的数组 ( ["title", "foo"] )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM