28

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.)

Hans Z.
  • 50,496
  • 12
  • 102
  • 115
Steve Bennett
  • 114,604
  • 39
  • 168
  • 219

1 Answers1

42

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 
Hans Z.
  • 50,496
  • 12
  • 102
  • 115