32

I want to update a value in a dict, which I can only identify by another value in the dict. That is, given this input:

[
  {
    "format": "geojson",
    "id": "foo"
  },
  {
    "format": "geojson",
    "id": "bar"
  },
  {
    "format": "zip",
    "id": "baz"
  }
]

I want to change baz's accompanying format to 'csv':

[
  {
    "format": "geojson",
    "id": "foo"
  },
  {
    "format": "geojson",
    "id": "bar"
  },
  {
    "format": "csv",
    "id": "baz"
  }
]

I have found that this works:

jq 'map(if .id=="baz" then .format="csv" else . end)' my.json

But this seems rather verbose, so I wonder if there is a more elegant way to express this. jq seems to be missing some kind of expression selector, the equivalent of might be [@id='baz'] in xpath.

(When I started this question, I had [.[] |...], then I discovered map, so it's not quite as bad as I thought.)

1 Answer 1

44

A complex assignment is what you're looking for:

jq '(.[] | select(.id == "baz") | .format) |= "csv"' my.json

Perhaps not shorter but it is more elegant, as requested. See the last section of the docs at: http://stedolan.github.io/jq/manual/#Assignment

Edit: using map:

jq 'map((select(.id == "baz") | .format) |= "csv")' my.json 
3
  • Ah ha. I notice that there's a superfluous pipe (I think). So it could be: jq '(.[] | select(.id == "baz") .format) |= "csv"' my.json Commented Apr 21, 2015 at 14:52
  • 1
    Another variation: map(select(.id == "corangamite").format |= "csv") Commented Apr 21, 2015 at 14:56
  • yeah, good one; I've added a variant using map; I'm not sure about the notation with the omitted pipe
    – Hans Z.
    Commented Apr 21, 2015 at 15:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.