最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jsonata - Referencing a JSON key dynamically - Stack Overflow

programmeradmin3浏览0评论

My JSON object has keys that are strings that are dynamically generated with the json is created. Trying to access the first key doesn't seem to work.

This is my jsonata expression

(
    $firstDate := $keys(slice)[0];
    $.{
      "firstDate": $firstDate,
      "x": slice.$firstDate,
      "y": slice."Friday, February 28"
    }
)

And this is my input JSON

{
  "slice": {
    "Friday, February 28": [
      {
        "key": "friday"
      },
      {
        "key": "february"
      }
    ]
  }
}

I expect "x" to have the same value as "y".

{
  "firstDate": "Friday, February 28",
  "x": "Friday, February 28",
  "y": [
    {
      "key": "friday"
    },
    {
      "key": "february"
    }
  ]
}

My JSON object has keys that are strings that are dynamically generated with the json is created. Trying to access the first key doesn't seem to work.

This is my jsonata expression

(
    $firstDate := $keys(slice)[0];
    $.{
      "firstDate": $firstDate,
      "x": slice.$firstDate,
      "y": slice."Friday, February 28"
    }
)

And this is my input JSON

{
  "slice": {
    "Friday, February 28": [
      {
        "key": "friday"
      },
      {
        "key": "february"
      }
    ]
  }
}

I expect "x" to have the same value as "y".

{
  "firstDate": "Friday, February 28",
  "x": "Friday, February 28",
  "y": [
    {
      "key": "friday"
    },
    {
      "key": "february"
    }
  ]
}
Share Improve this question asked Feb 17 at 7:27 RiteshRitesh 131 silver badge2 bronze badges New contributor Ritesh is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
Add a comment  | 

1 Answer 1

Reset to default 2

Use the lookup() function. In JSONata Object functions

Signature: $lookup(object, key)

Returns the value associated with key in object. If the first argument is an array of objects, then all of the objects in the array are searched, and the values associated with all occurrences of key are returned.

(
    $firstDate := $keys(slice)[0];
    $.{
      "firstDate": $firstDate,
      "x": $lookup(slice, $firstDate),
      "y": slice."Friday, February 28"
    }
)

The result

{
  "firstDate": "Friday, February 28",
  "x": [
    {
      "key": "friday"
    },
    {
      "key": "february"
    }
  ],
  "y": [
    {
      "key": "friday"
    },
    {
      "key": "february"
    }
  ]
}
发布评论

评论列表(0)

  1. 暂无评论