使用jq更新字典数组中的一个值 [英] Update one value in array of dicts, using jq

查看:253
本文介绍了使用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"
  }
]

我想将baz的随附格式更改为"csv":

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

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

我发现这可行:

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

但这似乎很冗长,所以我想知道是否有一种更优雅的方式来表达这一点. jq似乎缺少某种表达式选择器,等效于xpath中的[@id='baz'].

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.

(当我开始这个问题时,我有[.[] |...],然后我发现了map,所以它并不像我想的那么糟糕.)

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

推荐答案

您要寻找的是复杂的作业:

A complex assignment is what you're looking for:

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

根据要求,也许不短,但更优雅.请参阅以下文档的最后一部分: http://stedolan.github.io/jq/manual/#Assignment

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

使用map:

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

这篇关于使用jq更新字典数组中的一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆