jmespath / jmespath.py

JMESPath is a query language for JSON.
http://jmespath.org
MIT License
2.17k stars 178 forks source link

Space in Key for Custom JSON Object ? #287

Closed adamency closed 1 year ago

adamency commented 2 years ago

I can't figure out how to declare a key in my custom JSON object with spaces in the name:

> aws ec2 describe-instances --query "Reservations[].Instances[].{Name: Tags[?Key == 'Name'].Value | [0], Id: InstanceId, State: State.Name, 'Public IP': PublicIpAddress, Type: InstanceType}" --output table

Bad value for --query Reservations[].Instances[].{Name: Tags[?Key == 'Name'].Value | [0], Id: InstanceId, State: State.Name, 'Public IP': PublicIpAddress, Type: InstanceType}: Expecting: ['quoted_identifier', 'unquoted_identifier'], got: literal: Parse error at column 103, token "Public IP" (LITERAL), for expression:
"Reservations[].Instances[].{Name: Tags[?Key == 'Name'].Value | [0], Id: InstanceId, State: State.Name, 'Public IP': PublicIpAddress, Type: InstanceType}"

Absolutely nothing to be found online about this, as all threads in search results deal with spaces in keys from the object we're querying from, not the object we're creating.

I have tried with backticks, single quotes, double quotes, escaped single & double quotes, quoted quotes, etc... nothing seems to work.

Minitour commented 2 years ago

Double quotes is the right way to go about this, however this seems like an issue with the AWS cli rather than the JMESPath libraries.

This works just fine:

{ "public ip": @.my.object }
jamesls commented 1 year ago

Yep, it's double quotes for keys with spaces in them (anything that doesn't qualify as a unquoted idenfitifer), and for CLI you'll need to make sure you're escaping the quotes in your shell. A quick way to double check the quoting is to prefix the command with echo, which will show you how the value the CLI receives. Note the escaped \" here:

~ $ echo aws ec2 describe-instances --query "Reservations[].Instances[].{Name: Tags[?Key == 'Name'].Value | [0], Id: InstanceId, State: State.Name, \"Public IP\": PublicIpAddress, Type: InstanceType}" --output table

aws ec2 describe-instances --query Reservations[].Instances[].{Name: Tags[?Key == 'Name'].Value | [0], Id: InstanceId, State: State.Name, "Public IP": PublicIpAddress, Type: InstanceType} --output table