我有一个类似于以下内容的JSON文件:
{
"people": {
"company": "Acme",
"department": "Dev",
"perks": {
"eat": "pizza",
"drink": "beer",
"play": "twister"
},
"names": [{
"last_name": "Smith",
"first_names": [{
"name": "Bill",
"nickname": "Billy"
},
{
"name": "Alice",
"nickname": "Al"
},
{
"name": "Mary",
"nickname": "Mare"
}
]
},
{
"last_name": "Brown",
"first_names": [{
"name": "Gil",
"nickname": "Gillie"
},
{
"name": "Bob",
"nickname": "Bobby"
},
{
"name": "Mary",
"nickname": "Big M"
}
]
},
{
"last_name": "Sanchez",
"first_names": [{
"name": "Gil",
"nickname": "Gilster"
},
{
"name": "Jose",
"nickname": "Jo"
},
{
"name": "Marlena",
"nickname": "Marly"
}
]
}
]
}
}
我正在寻找类似于以下内容的输出:
Acme
Dev
beer
Smith, Bill, Billy
Smith, Alice, Al
Smith, Mary, Mare
Brown, Gil, Gillie
Brown, Bob, Bobby
Brown, Mary, Big M
Sanchez, Gil, Gilster
Sanchez, Jose, Jo
Sanchez, Marlena, Marly
我正在使用此查询:
$ jq -r '.people | .company, .department, .perks.drink, (.names[] | "\(.last_name), \(.first_names[].name), \(.first_names[].nickname)")'
并获得此输出,显然是错误的:
Acme
Dev
beer
Smith, Bill, Billy
Smith, Alice, Billy
Smith, Mary, Billy
Smith, Bill, Al
Smith, Alice, Al
Smith, Mary, Al
Smith, Bill, Mare
Smith, Alice, Mare
Smith, Mary, Mare
Brown, Gil, Gillie
Brown, Bob, Gillie
Brown, Mary, Gillie
Brown, Gil, Bobby
Brown, Bob, Bobby
Brown, Mary, Bobby
Brown, Gil, Big M
Brown, Bob, Big M
Brown, Mary, Big M
Sanchez, Gil, Gilster
Sanchez, Jose, Gilster
Sanchez, Marlena, Gilster
Sanchez, Gil, Jo
Sanchez, Jose, Jo
Sanchez, Marlena, Jo
Sanchez, Gil, Marly
Sanchez, Jose, Marly
Sanchez, Marlena, Marly
似乎.first_names[].nickname
的每个条目都被循环.first_names[].name
,产生了可见的输出,但是我不明白为什么。
答案 0 :(得分:3)
嗯,这是“应该如何知道您想要的是什么?”的情况。每当\()
插值表达式返回多个项目时,jq都会在插入每个项目时复制输出字符串。如果几个插值每个这样做,则它们相乘。它不知道您要并行迭代。
您可以明确写下您想要的内容:
jq -r '.people |
.company, .department, .perks.drink,
(.names[] | .last_name as $last |
.first_names[] |
"\($last), \(.name), \(.nickname)"
)'