Using the dictionary:
d = {'1': 'a'}
How can I extract the value a
using the JMESPath library in Python?
The following attempts did not work:
import jmespath
value = jmespath.search("1", d)
# throws jmespath.exceptions.ParseError: invalid token
value = jmespath.search("'1'", d)
# returns the key '1' instead of the value 'a'
You can directly address an identifier if it is an unquoted-string
, so A-Za-z0-9_
and if the string starts with A-Za-z_
.
From the grammar rule listed above identifiers can be one or more characters, and must start with A-Za-z_.
An identifier can also be quoted. This is necessary when an identifier has characters not specified in theunquoted-string
grammar rule. In this situation, an identifier is specified with a double quote, followed by any number ofunescaped-char
orescaped-char
characters, followed by a double quote.
Source: JMESPath documentation, Identifiers
Since your identifier is 0-9
, you have to use double quoted string for this identifier, so "1"
.
So, your working Python code would be:
import jmespath
d = {'1': 'a'}
value = jmespath.search('"1"', d)
print(value)