Search code examples
jsonshellcurlpipedrive-api

Grep a JSON field using Shell


I'm looking to cURL a url and then parse the JSON response and fetch a few of the field values using Shell, but I'm having some trouble parsing the JSON.

Here is the JSON I get back from the server:

{
  "success": true,
  "data": [
    {
      "period_start": "2014-04-01",
      "period_end": "2014-04-30",
      "deals": [
        {
          "id": 181,
          "user_id": 181551,
          "person_id": 261,
          "org_id": 243,
          "stage_id": 5,
          "title": "Customer deal",
          "value": 1500,
          "currency": "SEK",
          "add_time": "2014-04-08 07:13:11",
          "update_time": "2014-04-14 07:19:35",
          "stage_change_time": "2014-04-11 14:27:27",
          "active": false,
          "deleted": false,
          "status": "won",
          "next_activity_date": null,
          "next_activity_time": null,
          "next_activity_id": null,
          "last_activity_id": 220,
          "last_activity_date": "2014-04-11",
          "lost_reason": null,
          "visible_to": "0",
          "close_time": "2014-04-11 14:27:37",
          "pipeline_id": 1,
          "won_time": "2014-04-11 14:27:37",
          "lost_time": null,
          "products_count": null,
          "files_count": null,
          "notes_count": 1,
          "activities_count": 1,
          "undone_activities_count": 0,
          "expected_close_date": "2014-04-11",
          "stage_order_nr": 7,
          "person_name": "Name",
          "org_name": "Name",
          "next_activity_subject": null,
          "next_activity_type": null,
          "next_activity_duration": null,
          "next_activity_note": null,
          "formatted_value": "SEK1,500",
          "rotten_time": null,
          "weighted_value": 1500,
          "formatted_weighted_value": "SEK1,500",
          "org_hidden": false,
          "person_hidden": false
        }
      ],
      "totals": {
        "count": 5,
        "values": {
          "SEK": 18510
        },
        "weighted_values": {
          "SEK": 18510
        },
        "open_count": 0,
        "open_values": [

        ],
        "weighted_open_values": [

        ],
        "won_count": 5,
        "won_values": {
          "SEK": 18510
        }
      }
    }
  ]
}

The function I need help with:

function getTotalForMonth {
    url="http://api.pipedrive.com/v1/deals/timeline?start_date=2014-04-01&interval=month&amount=1&field_key=won_time&api_token=$auth_token"
    curl $url
    #What I'd like to do here is simply grep the "won_values" field from the "totals" array.
}

Solution

  • Use a proper JSON command-line parser like jq:

    $ curl "${url}" | jq '.data[0].totals | .won_count'
    5