使用 jq 根据对象中变量的值选择对象 [英] Select objects based on value of variable in object using jq

查看:38
本文介绍了使用 jq 根据对象中变量的值选择对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 json 文件:

I have the following json file:

{
    "FOO": {
        "name": "Donald",
        "location": "Stockholm"
    },
    "BAR": {
        "name": "Walt",
        "location": "Stockholm"
    },
    "BAZ": {
        "name": "Jack",
        "location": "Whereever"
    }
}

我正在使用 jq 并想获取名称"'location' 为 'Stockholm' 的对象元素.

I am using jq and want to get the "name" elements of the objects where 'location' is 'Stockholm'.

我知道我可以通过以下方式获取所有名称

I know I can get all names by

cat json | jq .[] | jq ."name"
"Jack"
"Walt"
"Donald"

但我无法弄清楚如何仅打印某些对象,给定子键的值(此处:location":Stockholm").

But I can't figure out how to print only certain objects, given the value of a sub key (here: "location" : "Stockholm").

推荐答案

改编自 用jq处理JSON,可以使用select(bool) 像这样:

Adapted from this post on Processing JSON with jq, you can use the select(bool) like this:

$ jq '.[] | select(.location=="Stockholm")' json
{
  "location": "Stockholm",
  "name": "Walt"
}
{
  "location": "Stockholm",
  "name": "Donald"
}

这篇关于使用 jq 根据对象中变量的值选择对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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