Axel Hanikel Axel Hanikel - 1 year ago 51
JSON Question

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
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!

Answer Source

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"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download