2014-04-24 50 views
1

我期待cURL一個URL,然後解析JSON響應並使用Shell獲取一些字段值,但我在解析JSON時遇到了一些麻煩。使用殼牌grep一個JSON字段

這裏是JSON我回來從服務器:

{ 
    "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 
     } 
     } 
    } 
    ] 
} 

我需要幫助的功能:

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. 
} 
+0

以python爲例,你可以做到這一點非常簡單 – pmod

+0

檢查相似解決方案在這裏:http://stackoverflow.com/questions/352098/how-can-i-pretty-print-json – pmod

回答

1

使用適當的JSON命令行解析器像jq

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

謝謝你一個很好的答案。爲了確認,這不是內置於Shell/bash本身的權利? – user2656127

+0

@ user2656127不,不幸的是;-) –