隐讳

问题描述 投票:1回答:2

如何在jq中表达一个不区分大小写的简单键引用?

例如,我可以有

{
  "key" : "value"
}

或者...

{
  "kEy" : "value"
}

而不是

{
  "key" : "value",
  "kEy" : "value"
}

有没有一种方法来表达 .key 过滤器,使其能够捕获 "key""kEy" ?

jq
2个回答
3
投票

一种方法是将所有的键都转换为小写作为默认格式,并提取你所选择的键名(灵感来自于这个 "小写")。峰的回答)

with_entries( .key |= ascii_downcase ).key

.key 里面 with_entries(..) 不能与您选择的键名相混淆,因为当使用*entries系列函数时,所有键名都是默认的。jq - with_entries, to_entriesfrom_entries

如果你的键是嵌套在其他对象里面的,其中一个会是 walk 通过整个JSON来递归重命名键,并获取你所选择的字段。

def recursive_key_rename:
  walk( if type == "object" then with_entries( .key |= ascii_downcase ) else . end);

recursive_key_rename | .key.anotherkey

请看 jq-play演示


3
投票

鉴于 i 旗帜 test 内置的匹配不区分大小写,你可以将它与 to_entries. 例如::

to_entries[] | select(.key | test("key"; "i")) .value

在线演示

© www.soinside.com 2019 - 2024. All rights reserved.