karan
karan

Reputation: 65

update part of a value of a json object using JQ

Have a value inside a JSON object with a variable that needs to be updated using JQ, below is my son file and jq command I'm using to update accountid in json file

{"bucketname":"test/$accountid/123","objectname":"test/$accountid/123","targetlocation":"$TARGET_LOCATION"}

JQ Command

jq 'map(.$accountid = "123")' myjson.json

Error

jq: error (at myjson.json:1): Cannot index string with string "$accountid"

I'm I missing something here?

Upvotes: 0

Views: 814

Answers (1)

peak
peak

Reputation: 116870

From the comments, it would appear you should be using map_values and perhaps something like sub. Consider therefore this example:

echo '{"bucketname":"test/$accountid/123","objectname":"test/$accountid/123","targetlocation":"$TARGET_LOCATION"}' |
 jq 'map_values( sub("[$]accountid";"123") )'

produces:

{
  "bucketname": "test/123/123",
  "objectname": "test/123/123",
  "targetlocation": "$TARGET_LOCATION"
}

Sharpening

You might want to sharpen the criteria for substituion, e.g.

sub("[$]accountid(?<tail>(/|$))"; "123\(.tail)" ) 

Upvotes: 1

Related Questions