JSON -> csv 创建标题行并填充标题(如果发现空字段)

JSON -> csv 创建标题行并填充标题(如果发现空字段)

我在 bash 中有一个程序,它可以获取 JSONline 文件,每行包含数百万个此类对象(请参阅来源

{
  "company_number": "09626947",
  "data": {
    "address": {
      "address_line_1": "Troak Close",
      "country": "England",
      "locality": "Christchurch",
      "postal_code": "BH23 3SR",
      "premises": "9",
      "region": "Dorset"
    },
    "country_of_residence": "United Kingdom",
    "date_of_birth": {
      "month": 11,
      "year": 1979
    },
    "etag": "7123fb76e4ad7ee7542da210a368baa4c89d5a06",
    "kind": "individual-person-with-significant-control",
    "links": {
      "self": "/company/09626947/persons-with-significant-control/individual/FFeqke7T3LvGvX6xmuGqi5SJXAk"
    },
    "name": "Ms Angela Lynette Miller",
    "name_elements": {
      "forename": "Angela",
      "middle_name": "Lynette",
      "surname": "Miller",
      "title": "Ms"
    },
    "nationality": "British",
    "natures_of_control": [
      "significant-influence-or-control"
    ],
    "notified_on": "2016-06-06"
  }
}

我的 JQ 查询如下所示:

for file in psc_chunk_*; do
jq --slurp --raw-output 'def pad($n): range(0;$n) as $i | 
.[$i]; ([.[] | .data.natures_of_control | length] | max) as $mx |
.[] | 
select(.data) |
[.company_number, .data.kind, .data.address.address_line_1, .data.address.country, .data.address.locality, .data.address.postal_code, .data.address.premises, .data.identification.country_registered, .data.identification.legal_authority, .data.identification.legal_form, .data.identification.place_registered, .data.identification.registration_number, .data.ceased_on, .data.country_of_residence, "\(.data.date_of_birth.year)-\(.data.date_of_birth.month)", .data.etag, .data.links.self, .data.name, .data.name_elements.title, .data.name_elements.forename, .data.name_elements.middle_name, .data.name_elements.surname, .data.nationality, .data.notified_on, (.data.natures_of_control | pad($mx))] |
@csv' $file > $file.csv;
done

这可能会伤害许多 JQ 专业人士的眼睛 - 它在提取键:值对方面效率不高,并且如果提供者碰巧更改了键的名称,我的代码将不再工作。

有没有办法将所有 json 压平为 csv将键保留为标头- 额外的困难是有一个natures_of_control包含不同数量条目的列表(为此我使用 pad 函数来获得矩形结果)。

答案1

尝试使用米勒(https://github.com/johnkerl/miller), 跑步

mlr --j2c unsparsify input.json>output.csv

相关内容