How do I sum the values in an array of maps in jq?

前端 未结 3 1477
不思量自难忘°
不思量自难忘° 2020-12-08 14:50

Given a JSON stream of the following form:

{ \"a\": 10, \"b\": 11 } { \"a\": 20, \"b\": 21 } { \"a\": 30, \"b\": 31 }

I would like to sum t

3条回答
  •  不知归路
    2020-12-08 15:20

    I faced the same question when listing all artifacts from GitHub (see here for details) and want to sum their size.

    curl https://api.github.com/repos/:owner/:repo/actions/artifacts \
         -H "Accept: application/vnd.github.v3+json" \
         -H "Authorization:  token " \
         | jq '.artifacts | map(.size_in_bytes) | add'
    

    Input:

    {
      "total_count": 3,
      "artifacts": [
        {
          "id": 0000001,
          "node_id": "MDg6QXJ0aWZhY3QyNzUxNjI1",
          "name": "artifact-1",
          "size_in_bytes": 1,
          "url": "https://api.github.com/repos/:owner/:repo/actions/artifacts/2751625",
          "archive_download_url": "https://api.github.com/repos/:owner/:repo/actions/artifacts/2751625/zip",
          "expired": false,
          "created_at": "2020-03-10T18:21:23Z",
          "updated_at": "2020-03-10T18:21:24Z"
        },
        {
          "id": 0000002,
          "node_id": "MDg6QXJ0aWZhY3QyNzUxNjI0",
          "name": "artifact-2",
          "size_in_bytes": 2,
          "url": "https://api.github.com/repos/:owner/:repo/actions/artifacts/2751624",
          "archive_download_url": "https://api.github.com/repos/:owner/:repo/actions/artifacts/2751624/zip",
          "expired": false,
          "created_at": "2020-03-10T18:21:23Z",
          "updated_at": "2020-03-10T18:21:24Z"
        },
        {
          "id": 0000003,
          "node_id": "MDg6QXJ0aWZhY3QyNzI3NTk1",
          "name": "artifact-3",
          "size_in_bytes": 3,
          "url": "https://api.github.com/repos/docker/mercury-ui/actions/artifacts/2727595",
          "archive_download_url": "https://api.github.com/repos/:owner/:repo/actions/artifacts/2727595/zip",
          "expired": false,
          "created_at": "2020-03-10T08:46:08Z",
          "updated_at": "2020-03-10T08:46:09Z"
        }
      ]
    }
    

    Output:

    6
    

提交回复
热议问题