Search code examples
jsonjq

What is jq '.key["value"]'?


jq '.key["value"]' config.json is found in some of our bash scripts and when I tested it, it seems to be doing the same thing that jq '.key.value' config.json does. So I am not sure why the latter (which I see everywhere else) is not used instead. I tried to research this notation but found nothing.

Thanks in advance!


Solution

  • .key[ "value" ] and .key.value are equivalent.

    These are specific uses of EXPR[ EXPR2 ] and EXPR.IDENT, two syntax for indexing. The differences in syntax impose the following differences in functionality:

    • EXPR.IDENT requires a hard-coded identifier.
    • EXPR[ EXPR2 ] accepts an expression which is evaluated at run-time.
    • EXPR[ EXPR2 ]'s EXPR2 isn't limited to return identifiers.
    • EXPR[ EXPR2 ]'s EXPR2 isn't limited to return strings.

    While any uses of EXPR.IDENT can be converted to the EXPR[ EXPR2 ] syntax, the above means there's no way to convert the following uses of EXPR[ EXPR2 ] into the EXPR.IDENT syntax:

    • EXPR[ $key ] (The value of $key isn't known during development.)
    • EXPR[ "foo.bar" ] (foo.bar isn't an identifier.)
    • EXPR[ 0 ], to access an array element. (0 isn't an identifier.)