如何使用JQ从JSON父和子父参数捕获值?

时间:2017-03-07 08:55:54

标签: json jq

我有以下JSON文件,我需要使用JQ捕获,但到目前为止我只设法捕获父参数(SUBSCRIBER_ID),但无法捕获子父参数,即"提供&#34 ;

需要你的帮助提供正确的JQ过滤器以捕获" SUBSCRIBER_ID"和"提供"值。

JSON

{"Data1": [
   {"Data2": {
          "SUBSCRIBER_ID" : "999050280010099",
          "MSISDN" : "999050280010099",
          "EMAIL" : "john@email.com",
          "OFFERS" : [
                  {
                       "Offer" : 12344,
                       "EffectiveDate" : "1488787236",
                       "ExpiryDate" : "4070869200"
                  }               ],
          "IsGroup" : "false",
     }}
]}

我的JQ过滤器无法正常工作

'.Data1 | .[] | .Data2 | to_entries |  map(.value) | @csv' -r

预期输出:

SUBSCRIBER_ID,Offer
999050280010099,12344

1 个答案:

答案 0 :(得分:1)

您可以试试jq

jq -r '.Data1|.[]|.Data2|[.SUBSCRIBER_ID, .OFFERS[].Offer]|@csv' file > out.csv

(或)根据@peak的建议,

jq -r '.Data1[].Data2|[.SUBSCRIBER_ID, .OFFERS[].Offer]|@csv' file

另一种方法:

jq -r '.[]|.[]|map([.SUBSCRIBER_ID, .OFFERS[].Offer])|.[]|@csv' file

<强>输入:

$ cat file.json
{
  "Data1": [
    {
      "Data2": {
        "SUBSCRIBER_ID": "999050280010099",
        "MSISDN": "999050280010099",
        "EMAIL": "john@email.com",
        "OFFERS": [
          {
            "Offer": 12344,
            "EffectiveDate": "1488787236",
            "ExpiryDate": "4070869200"
          }
        ],
        "IsGroup": "false"
      }
    }
  ]
}

<强>测试

$ jq -r '.Data1|.[]|.Data2|[.SUBSCRIBER_ID, .OFFERS[].Offer]|@csv' file.json
"999050280010099",12344

$ jq -r '.[]|.[]|map([.SUBSCRIBER_ID, .OFFERS[].Offer])|.[]|@csv' file.json
"999050280010099",12344