pythonjmespath

Accessing values in a dictionary with JMESPath in Python when the value is an integer (e.g.: 1)


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'

Solution

  • 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 the unquoted-string grammar rule. In this situation, an identifier is specified with a double quote, followed by any number of unescaped-char or escaped-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)