使用jq格式化json数据

时间:2017-08-18 21:15:19

标签: json unix jq

我正在尝试将json从以下格式转换为其他格式,但我无法生成所需的格式格式:

输入Json:

[  
   {  
      "name":"Successful retrieval",
      "elements":[  
         {  
            "scenario":"First",
            "steps":[  
               {  
                  "name":"as a customer",
                  "result":{  
                     "status":"passed",
                     "duration":29428
                  }
               },
               {  
                  "name":"I hit API",
                  "result":{  
                     "status":"passed",
                     "duration":210403731
                  }
               },
               {  
                  "name":"API should respond",
                  "result":{  
                     "status":"passed",
                     "duration":1246183
                  }
               }
            ]
         }
      ]
   }
]

所需格式:

    {  
   "name":"Successful retrieval",
   "Result":[  
      {  
         "stepName":"as a customer",
         "status":"passed"
      },
      {  
         "stepName":"I hit API",
         "status":"passed"
      },
      {  
         "stepName":"API should respond",
         "status":"passed"
      }
   ]
}

使用的JQ命令:

  jq ['.[] | { name: .name, steps: .elements[].steps[]} | 
{name:.name, stepName:.steps.name, status:.steps.result.status}']

使用上面的命令,我得到以下格式:

[
  {
    "name": "Successful retrieval",
    "stepName": "as an  Synapse API customer",
    "status": "passed"
  },
  {
    "name": "Successful retrieval",
    "stepName": "I hit API",
    "status": "passed"
  },
  {
    "name": "Successful retrieval",
    "stepName": "API should respond",
    "status": "passed"
  }
]

我尝试使用join,但它没有用。任何指针都会有所帮助。 提前谢谢。

2 个答案:

答案 0 :(得分:3)

这是一个解决方案:

  .[]
| .Result = [
      .elements[]
    | .steps[]
    | {stepName:.name, status:.result.status}
  ]
| del(.elements)

这是一个示例运行,假设您的数据位于input.json

$ jq '.[] | .Result = [.elements[] | .steps[] | {stepName:.name, status:.result.status}] | del(.elements)' input.json
{
  "name": "Successful retrieval",
  "Result": [
    {
      "stepName": "as a customer",
      "status": "passed"
    },
    {
      "stepName": "I hit API",
      "status": "passed"
    },
    {
      "stepName": "API should respond",
      "status": "passed"
    }
  ]
}

答案 1 :(得分:1)

这只是jq170727答案的一个小变化。

最后一步是从您想要的部分构建对象,而不是删除您不想要的部分。

jq '.[]
| .Result =
  [  
     .elements[]
     | .steps[]
     | { stepName:.name, status:.result.status }
  ]
| { name, Result }'