Invalid path expression near attempt to access element
Asked Answered
H

1

7

When trying to change a single element in an array, I get Invalid path expression near attempt to access element - but only when the array is captured from --rawInput.

Example:

# input: [ 1, 0 ]
. as $list | $list[0] = 30
# output: [ 30, 0 ]

But this doesn't work:

# input: 1,0
split(",") | map(tonumber) as $list | $list[0] = 30
# Invalid path expression near attempt to access element 0 of [1,0]

Any ideas?

Horizontal answered 13/12, 2019 at 14:37 Comment(0)
A
9

Your attempt failed because of following :

Note that the LHS of assignment operators refers to a value in .. Thus $var.foo = 1 won’t work as expected ($var.foo is not a valid or useful path expression in .); use $var | .foo = 1 instead.

From the Assignment section of the jq manual.

It likely only worked in your first jq command because $list and . were equal.

Following that you could have used the following :

split(",") | map(tonumber) as $list | $list | .[0] = 30

Or more simply in your case :

split(",") | map(tonumber) | .[0]=30
Amaro answered 13/12, 2019 at 14:39 Comment(1)
Oh gosh, I hadn't quite realised that at all, but it works perfectly, thank you 👍Horizontal

© 2022 - 2024 — McMap. All rights reserved.