I have the following json file:

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

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"

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

推荐答案

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"
}

Json相关问答推荐

仅在通过Jolt输入时才级联Json的值

SSIS Kingswaysoft Json源动态 node 名称

基于两个条件替换扁平化的SON中的值

如何使用Laravel在MariaDB JSON kolumn中使用unicode字符

如何在PowerShell中扩展JSON中的嵌套数组

在Golang中从 struct 手动创建JSON对象

使用JQ将JSON输出转换为CSV复杂 struct

在 SQL 存储过程中使用参数 Select 值

在 python 中循环 JSON 数组

Vega-Lite规范:尽管在规范中提供了数据,但显示空图表

在 CodePipeline 中调用 lambda 时传递用户参数

jq可以在两个JSON对象列表中依次添加对象吗?

Powershell v7 文本背景突出显示

如何在 Android Studio 中将 List 字段作为空列表[]返回?

Scala - 在构建 Json 时无法删除 Key -> value "{}" 大括号的双引号

没有很多类的 GSON 解析

以 unicode 将 pandas DataFrame 写入 JSON

春天:返回@ResponseBodyResponseEntity>

从 JSON 到 JSONL 的 Python 转换

如果键可能不存在,则从 Python dict 读取