将JSON从Raw格式解析为CSV以获得新手

时间:2017-08-30 14:17:57

标签: json csv parsing

我正在寻找一种方法将RAW JSON解析为CSV,我对编码,编程等方面的任何事都是新手。我发现了一个完全符合我需要的网站https://json-csv.com/但是我正在解析的数据集大于他们的免费金额,所以我基本上每月支付10美元用于我认为可以通过宏观或者我能想到的东西来完成的事情。

我基本上正在寻找一种快速方法将下面的块解析为基于列的结构化详细信息。列将是:Key,Value,Context_Geography,Context_CompanyID,Context_ProductID,Description,Created by,Updated by,updated date。

{ “策略”:[{ “键”: “viaPayEnabledRates”, “值”: “”, “上下文”:{ “地理”: “”, “companyID”: “” “的productID”: “”}, “CREATED_BY”: “0”, “updated_by”: “0”, “updated_date”: “2014-03-24T21:22:25.420 + 0000”},{“键“:” viaPayEnabledRates “ ”值“: ”[\“ WSPNConsortia \”,\ “WSPNNegotiated \”,\ “WSPNPublished \”] “ ”上下文“:{ ”地理“: ”“,” companyID “:”*“,”productID“:”60003“},”description“:”Central Payment Pilot“,”created_by“:”10130590“,”updated_by“:”10130590“,”updated_date“:”2016-04- 05T07:51:29.043 + 0000" }

1 个答案:

答案 0 :(得分:0)

以下是使用jq

的解决方案

如果文件filter.jq包含

def headers:
  [
    "Key", "Value", "Context_Geography", "Context_CompanyID", "Context_ProductID",
    "Description", "Created by", "Updated by", "updated date"
  ]
;

def fields:
  [
    .key, .value, .context.geography, .context.companyID, .context.productID,
    .description, .created_by, .updated_by, .updated_date
  ]
;

  headers, (.policies[] | fields)
| @csv

并且文件data.jq包含您的示例数据

 {
  "policies": [
    {
      "key": "viaPayEnabledRates",
      "value": "",
      "context": {
        "geography": "",
        "companyID": "",
        "productID": ""
      },
      "created_by": "0",
      "updated_by": "0",
      "updated_date": "2014-03-24T21:22:25.420+0000"
    },
    {
      "key": "viaPayEnabledRates",
      "value": "[\"WSPNConsortia\",\"WSPNNegotiated\",\"WSPNPublished\"]",
      "context": {
        "geography": "",
        "companyID": "*",
        "productID": "60003"
      },
      "description": "Central Payment Pilot",
      "created_by": "10130590",
      "updated_by": "10130590",
      "updated_date": "2016-04-05T07:51:29.043+0000"
    }
  ]
}

然后以

运行jq
jq -M -r -f filter.jq data.json

产生输出

"Key","Value","Context_Geography","Context_CompanyID","Context_ProductID","Description","Created by","Updated by","updated date"
"viaPayEnabledRates","","","","",,"0","0","2014-03-24T21:22:25.420+0000"
"viaPayEnabledRates","[""WSPNConsortia"",""WSPNNegotiated"",""WSPNPublished""]","","*","60003","Central Payment Pilot","10130590","10130590","2016-04-05T07:51:29.043+0000"