简体   繁体   中英

How to extract part of an aeson value that satisfies a condition?

I have a JSON structure which looks like this:

{
  "instances": [
    {
      "instanceId": "i-1234",
      "tags": [
        {
          "value": "author1useast1",
          "key": "hostname"
        }
      ]
    },
    {
      "instanceId": "i-5678",
      "tags": [
        {
          "value": "proxy1useast1",
          "key": "hostname"
        }
      ]
    }
  ]
}

I would like to get a list of all instances/instanceId where instances/tags has a hostname of author1useast1 .

I have thought about getting a list of instances with key "instances" . _Values key "instances" . _Values first, then mapping it into a list of ( instanceId , tags ) tuples and then doing the filtering. However that looks very inefficient to me.

Is there a more elegant / idiomatic way of doing this?

Thanks a lot!

If you want to use lens, you can use filtered optic, as instance:

  key "instances" . values
. filtered (anyOf (key "tags" . values) $
    allOf (key "key") (=="hostname")
    <&&> allOf (key "value") (=="author1useast1"))
. key "instanceId"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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