我正在尝试解析这样的JSON对象集合:
{
"stage": [
{
"name": "Stage 1",
"weeks": [
{
"name": "Week 1",
"matches": [
{
"teams": [
{
"name": "San Francisco Shock",
"score": "0",
"score_url": "https://overwatchleague.com/matches/10223"
},
{
"name": "Los Angeles Valiant",
"score": "4",
"score_url": "https://overwatchleague.com/matches/10223"
}
]
},
{
"teams": [
{
"name": "Shanghai Dragons",
"score": "0",
"score_url": "https://overwatchleague.com/matches/10224"
},
{
"name": "Los Angeles Gladiators",
"score": "4",
"score_url": "https://overwatchleague.com/matches/10224"
}
]
},
{
"teams": [
{
"name": "Dallas Fuel",
"score": "1",
"score_url": "https://overwatchleague.com/matches/10225"
},
{
"name": "Seoul Dynasty",
"score": "2",
"score_url": "https://overwatchleague.com/matches/10225"
}
]
},
等等,
我正试图将其转换为一种格式,使另一种对JSON不太友好的语言可以通过将其压缩为以下格式来更轻松地处理:
{"matches":
[
{
"team1": "San Francisco Shock",
"t1score": "0",
"team2": "Los Angeles Valiant",
"t2score": "4"
},
{ ... }
]
}
我正在尝试使用此jq过滤器来完成此操作:
jq '.stage[] | {matches: [{team1: .weeks[].matches[].teams[0].name, t1score:
.weeks[].matches[].teams[0].score, team2: .weeks[].matches[].teams[1].name,
t2score: .weeks[].matches[].teams[1].score}]}'
与此相关的问题是,它将“名称”键的每个实例与值“ San Francisco Shock”的值匹配到数组“匹配”中所有分数和名称的排列。我对jq还是很陌生,但是我认为这正在发生,因为我只是告诉它通过过滤器将“周”和“匹配”中的所有元素映射在一起。它是否正确?实际执行我想要尝试并看起来像的过滤器是什么?我还没有找到一种简单的方法来使过滤器不匹配超出“团队”数组的范围。
答案 0 :(得分:0)
技巧是将.weeks[]
迭代器向前“拉”,并在map
数组上.matches
:
.stage[]
|.weeks[]
| {matches:
(.matches
| map({team1: .teams[0].name,
t1score: .teams[0].score,
team2: .teams[1].name,
t2score: .teams[1].score }) ) }
{
"matches": [
{
"team1": "San Francisco Shock",
"t1score": "0",
"team2": "Los Angeles Valiant",
"t2score": "4"
},
{
"team1": "Shanghai Dragons",
"t1score": "0",
"team2": "Los Angeles Gladiators",
"t2score": "4"
},
{
"team1": "Dallas Fuel",
"t1score": "1",
"team2": "Seoul Dynasty",
"t2score": "2"
}
]
}