如何创建从2个单独级别的JSON文件提取数据的jq查询?

时间:2019-09-28 01:01:18

标签: json jq

我有一个看起来像这样的JSON文件:

{
    "people": {
        "company": "Acme",
        "department": "Dev",
        "perks": {
            "eat": "pizza",
            "drink": "beer",
            "play": "twister"
        },
        "names": [{
                "last_name": "Smith",
                "first_names": [{
                        "name": "Bill"
                    },
                    {
                        "name": "Alice"
                    },
                    {
                        "name": "Mary"
                    }
                ]
            },
            {
                "last_name": "Brown",
                "first_names": [{
                        "name": "Gil"
                    },
                    {
                        "name": "Bob"
                    },
                    {
                        "name": "Mary"
                    }
                ]
            },
            {
                "last_name": "Sanchez",
                "first_names": [{
                        "name": "Gil"
                    },
                    {
                        "name": "Jose"
                    },
                    {
                        "name": "Marlena"
                    }
                ]
            }
        ]
    }
}

我正在寻找的输出是:

acme
Dev
twister
Smith, Bill
Smith, Alice
Smith, Mary
Brown, Gil
Brown, Bob
Brown, Mary
Sanchez, Gil
Sanchez, Jose
Sanchez, Marlena

我有一个获取名称的jq查询:

jq -r '.people | .names[] | "\(.last_name), \(.first_names[].name)"'

并且我得到的查询使我获得了前三行(Acme,Dev,twister):

jq -r '.people | .company, .department, .perks.play'

但是当我尝试将它们组合在一起(以多种方式在此处列出!)时,出现错误。我不知道如何结合使用这些查询,以使查询走到“ .people”之下的第一层,然后走到“ .people.names []”之下的层(全部在一个查询中)。

1 个答案:

答案 0 :(得分:1)

只需使用“,”运算符将两个查询结合起来,例如

.people
| (.company, .department, .perks.play),
  (.names[] | "\(.last_name), \(.first_names[].name)")