【问题标题】:Grep a JSON field using Shell使用 Shell 对 JSON 字段进行 Grep
【发布时间】:2014-04-24 18:39:38
【问题描述】:

我正在寻找 cURL 一个 url,然后解析 JSON 响应并使用 Shell 获取一些字段值,但我在解析 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.
}

【问题讨论】:

标签: json shell curl pipedrive-api


【解决方案1】:

使用适当的 JSON 命令行解析器,例如 jq:

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

【讨论】:

  • 感谢您的出色回答。确认一下,这不是原生的 Shell/bash 内置的吗?
  • @user2656127 不,很遗憾不是 ;-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-02-07
  • 1970-01-01
  • 2023-03-23
  • 2021-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多