0

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.,

  • query 'Reservations[].Instances[].[InstanceId,NetworkInterfaces[].Groups[].GroupId,NetworkInterfaces[].SubnetId]' works, but when I tried to adapt it to
  • query '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.

xpt
  • 20,363
  • 37
  • 127
  • 216
  • 1
    The error is clear `Expecting: colon, ...`. A key is missing in the dictionary, e.g. `, key: NetworkInterfaces[].` Open a new question if you have other issues. – Vladimir Botka Sep 28 '22 at 14:54

1 Answers1

1

See MultiSelect Hash. For example,

>>> import jmespath
>>> expression = jmespath.compile('{a: a}')
>>> expression.search({"a": "foo", "b": "bar", "c": "baz"})
{'a': 'foo'}
Vladimir Botka
  • 58,131
  • 4
  • 32
  • 63
  • Thanks Vladimir, I made the simple returning {"a": "foo"} works but not for more complicates situations. Please see the updated OP and see if you can identify the problem. Thx!! – xpt Sep 28 '22 at 14:20
  • Make the case [mre]. Your first question is an excellent example. The second one is exactly the opposite. – Vladimir Botka Sep 28 '22 at 14:36
  • Sorry, didn't expecting that data from aws doc would be full of errors -- I've already corrected two obvious ones, which is why I said _"or better"_. This is the one that should be working: ~~https://pastebin.com/vR3BA3b5~~. This one: https://pastebin.com/DSV6BvhN, verified! – xpt Sep 28 '22 at 15:03