twisteddebian
twisteddebian

Reputation: 3

Extracting a json string from child array in bash

This is the output I receive via curl. I want to save 'playcount' in a variable. How do I loop through tracks[] to get the strings 'playcount' and save them so I can form the sum?
I've spend a lot of time figuring it out with jq but nothing really worked out..

{
  "success": true,
  "data": {
    "track_count": 2,
    "discs": [
      {
        "number": 1,
        "name": "",
        "tracks": [
          {
            "album_id": "u2hh2n2b7fo20v46cbe",
            "playcount": 17212,
            "name": "World Savior",
            "number": 1,
            "duration": 341,
          },
          {
            "album_id": "jk299sdhjahj991nbwd",
            "playcount": 9812,
            "name": "Tower",
            "number": 2,
            "duration": 281,
          }
        ]
      }
    ],
    "month": 11,
    "day": 26,
    "year": 2021,
    "type": "single",
  }
}

Upvotes: 0

Views: 481

Answers (1)

Gordon Davisson
Gordon Davisson

Reputation: 126108

If you want the list of playcount values, you just have to drill down to the right content:

jq '.data.discs[].tracks[].playcount'

If you want their sum, make an array of that and add its entries:

jq '[.data.discs[].tracks[].playcount]|add'

Upvotes: 2

Related Questions