JMESPath can be used to query json but the return is no longer json any more:
E.g., searching {"a": "foo", "b": "bar", "c": "baz"}
with JMESPath a
will yield "foo"
.
How can I return {"a": "foo"}
instead?
jq is able to do it:
curl 'https://api.github.com/repos/stedolan/jq/commits?per_page=5' | jq '.[0] | {message: .commit.message, name: .commit.committer.name}'
{
"message": "Merge pull request #162 from stedolan/utf8-fixes\n\nUtf8 fixes. Closes #161",
"name": "Stephen Dolan"
}
UPDATE:
I made returning {"a": "foo"}
works but not for more complicates situation, like JMESPath query from AWS CLI to find EC2's security groups id and subnet id. I.e.,
'Reservations[].Instances[].[InstanceId,NetworkInterfaces[].Groups[].GroupId,NetworkInterfaces[].SubnetId]'
works, but when I tried to adapt it to'Reservations[].Instances[].{InstanceId: InstanceId, SubnetId: NetworkInterfaces[].Groups[].GroupId,NetworkInterfaces[].SubnetId}'
It then no longer working. Got error of:
Bad value for --query Reservations[].Instances[].{InstanceId: InstanceId, SubnetId: NetworkInterfaces[].Groups[].GroupId,NetworkInterfaces[].SubnetId}: Expecting: colon, got: flatten: Parse error at column 116, token "[]" (FLATTEN), for expression: "Reservations[].Instances[].{InstanceId: InstanceId, SubnetId: NetworkInterfaces[].Groups[].GroupId,NetworkInterfaces[].SubnetId}"
Is it the limitation of JMESPath or aws ec2 describe-instances
command?
You can get the sample input from https://awscli.amazonaws.com/v2/documentation/api/2.0.34/reference/ec2/describe-instances.html, or better, from https://pastebin.com/JaFwn5ZH.
See MultiSelect Hash. For example,
>>> import jmespath
>>> expression = jmespath.compile('{a: a}')
>>> expression.search({"a": "foo", "b": "bar", "c": "baz"})
{'a': 'foo'}