jq:将数组映射到 csv 字段 headers

jq: map arrays to csv field headers

有没有办法像这样导出 json:

{
   "id":"2261026",
   "meta":{
      "versionId":"1",
      "lastUpdated":"2021-11-08T15:13:39.318+01:00",
   },
   "address": [
      "string-value1",
      "string-value2"
   ],
   "identifier":[
      {
         "system":"urn:oid:2.16.724.4.9.20.93",
         "value":"6209"
      },
      {
         "system":"urn:oid:2.16.724.4.9.20.2",
         "value":"00042"
      },
      {
         "system":"urn:oid:2.16.724.4.9.20.90",
         "value":"UAB2"
      }
   ]
}
{
   "id":"2261027",
   "meta":{
      "versionId":"1",
      "lastUpdated":"2021-11-08T15:13:39.318+01:00",
   },
   "address": [
      "string-value1",
      "string-value2",
      "string-value3",
      "string-value4"
   ],
   "identifier":[
      {
         "system":"urn:oid:2.16.724.4.9.20.93",
         "value":"6205"
      },
      {
         "system":"urn:oid:2.16.724.4.9.20.2",
         "value":"05041"
      }
   ]
}

我想要这样的东西:

"id","meta_versionId","meta_lastUpdated","address","identifier0_system","identifier0_value","identifier1_system","identifier1_value","identifier2_system","identifier2_value"
"2261026","1","2021-11-08T15:13:39.318+01:00","string-value1|string-value2","urn:oid:2.16.724.4.9.20.93","6209","urn:oid:2.16.724.4.9.20.2","00042","urn:oid:2.16.724.4.9.20.90","UAB2"
"2261027","1","2021-11-08T15:13:39.318+01:00","string-value1|string-value2|string-value3|string-value4","urn:oid:2.16.724.4.9.20.93","6205","urn:oid:2.16.724.4.9.20.2","05041",,

简而言之:

address 数组字段字符串值必须映射并使用“|”连接其值特点。示例:"string-value1|string-value2"

identifiers 数组字段 objects 必须映射到 "n-field-header"。示例:"identifier0_system","identifier0_value","identifier1_system","identifier1_value","identifier2_system","identifier2_value,..."

有什么想法吗?

试试这个

jq -r '[
  .id,
  (.meta | .versionId, .lastUpdated),
  (.address | join("|")),
  (.identifier[] | .system, .value)
] | @csv'

Demo


要在 header 行前加上 identifierX_systemidentifierX_value 字段对的数量,使其与输入的最长 identifier 数组的长度相匹配,试试这个

jq -rs '[
  
  "id",
  "meta_versionId", "meta_lastUpdated",
  "address",
  (
    range([.[].identifier | length] | max)
    | "identifier\(.)_system", "identifier\(.)_value"
  )

], (.[] | [

  .id,
  (.meta | .versionId, .lastUpdated),
  (.address | join("|")),
  (.identifier[] | .system, .value)

]) | @csv'

Demo