Search code examples
pythonjsonjqgerrit

How to parse JSON output of gerrit query to extract data?


I have a scenario, where I am trying to extract some data from output of gerrit query. But unable to do using awk

Command:

ssh -p 29418 gerrit.abc.se gerrit query --format=JSON project:dddd status:merged branch:master change:Ie2ef9e47f --submit-records

Output of above command:

{
  "project": "dddd",
  "branch": "master",
  "id": "Ie2ef9e47fc6c046091d93521198bf0a1075cb77e",
  "number": 3984134,
  "subject": "adding configuration",
  "owner": {
    "name": "abc",
    "email": "abc.com",
    "username": "eshakuy"
  },
  "url": "https://gerrit.abc.se/3984134",
  "commitMessage": "adding configuration\n\nChange-Id: Ie2ef9e47fc6c046091d93521198bf0a1075cb77e\n",
  "createdOn": 1533208993,
  "lastUpdated": 1536301464,
  "open": false,
  "status": "MERGED",
  "submitRecords": [
    {
      "status": "OK",
      "labels": [
        {
          "label": "Verified",
          "status": "OK",
          "by": {
            "name": "ADP Automation",
            "username": "adpauto"
          }
        },
        {
          "label": "Code-Review",
          "status": "OK",
          "by": {
            "name": "abc",
            "email": "abc.com",
            "username": "eeeee"
          }
        }
      ]
    }
  ]
}
{
  "type": "stats",
  "rowCount": 1,
  "runTimeMilliseconds": 10,
  "moreChanges": false
}

What I want to extract from above output is:

submit Records:

label:Verified status:OK name:ADP Automation
lable:Code-Review status:OK name:abc

That is the only information I need to display/store in csv file.


Solution

  • You could use the jq program like in the following example:

    ssh -p 29418 gerrit.abc.se gerrit query --format=JSON project:dddd status:merged branch:master change:Ie2ef9e47f --submit-records |
     jq --raw-output '
       .submitRecords[]? 
       | .labels[]
       | .label + " = " + .status + " by " + .by.name'
    
    Code-Review => OK by Marcelo Avila de Oliveira
    Verification => OK by Gerrit
    

    See more info about the jq here.