首页 文章

如何阻止JQ过滤器将键匹配到其他键的每个排列

提问于
浏览
0

我正在尝试解析像这样的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}]}'

这个问题是,它匹配“名称”键的每个实例,其值为“旧金山震撼”,而不是数组“匹配”中所有分数和名称的排列 . 我对jq很新,但我认为这种情况正在发生,因为我只是告诉它通过过滤器将“周”和“匹配”中的所有元素映射到一起 . 它是否正确?什么过滤器实际上做了我想要尝试和看起来像?我还没有找到一种简单的方法来阻止过滤器超出“团队”数组的范围 .

1 回答

  • 0

    诀窍是 .weeks[] .weeks[] 迭代器前进,并通过 .matches 数组 map

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

相关问题