Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

json - Update one value in array of dicts, using jq

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...