简体   繁体   English

如何在 JQ 中打印键和值?

[英]How do I print the key along with the value in JQ?

For example, if I have the data below例如,如果我有以下数据

{
    "test1": {
        "name": "John"
    },
    "test2": {
        "name": "Jack"
    },
    "test3": {
        "name": "Jim"
    },
    "test4": {
        "name": "John"
    }
}

and I wanted to get all the items where the name property is John, in the following format我想获取 name 属性为 John 的所有项目,格式如下

{
    "test1": {
        "name": "John"
    },
    "test4": {
        "name": "John"
    }
}

How would I go about doing this?我该怎么做呢? If I use the following JQ command: .[] | select(.name | ascii_downcase | contains("john"))如果我使用以下 JQ 命令: .[] | select(.name | ascii_downcase | contains("john")) .[] | select(.name | ascii_downcase | contains("john")) it only returns .[] | select(.name | ascii_downcase | contains("john"))它只返回

{
  "name": "John"
}
{
  "name": "John"
}

omitting the keys.省略键。

要保持原始结构,请使用 map_values :

map_values(select(.name | ascii_downcase | contains("john")))

Use the update operator |= to (un)select each item while keeping the outer context:使用更新运算符|=来(取消)选择每个项目,同时保持外部上下文:

jq '.[] |= select(.name | ascii_downcase | contains("john"))'
{
  "test1": {
    "name": "John"
  },
  "test4": {
    "name": "John"
  }
}

Demo演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM