在转换为 CSV 之前,使用 JQ 将 JSON 嵌套对象输出到数组中

Use JQ to output JSON nested object into array, before conversion to CSV

在转换为 CSV 之前,使用 JQ 将 JSON 嵌套对象输出到数组中

问题是对先前解决方案的扩展:


数据来源:

{
  "Other": [],
  "Objects": [
    {
      "ObjectElementName": "Test 123",
      "ObjectElementArray": [],
      "ObjectNested": {
        "0": 20,
        "1": 10.5
      },
      "ObjectElementUnit": "1"
    },
    {
      "ObjectElementName": "Test ABC 1",
      "ObjectElementArray": [],
      "ObjectNested": {
        "0": 0
      },
      "ObjectElementUnit": "2"
    },
    {
      "ObjectElementName": "Test ABC 2",
      "ObjectElementArray": [],
      "ObjectNested": {
        "0": 15,
        "1": 20
      },
      "ObjectElementUnit": "5"
    }
  ],
  "Language": "en-US"
}

JQ命令解压[失败]

jq -r '.Objects[]
  | select(.ObjectElementName | test("ABC"))
  | [.ObjectElementName,.ObjectNested,.ObjectElementUnit]
  |@csv' input.json

需要输出 CSV(或变体,只要 ObjectNested 出现在 CSV 中的单个列中)

ObjectElementName,ObjectNested,ObjectElementUnit
"Test ABC 1","0:0","2"
"Test ABC 2","0:15,1:20","5"

有了keys_unsorted和字符串插值,很容易把ObjectNested变成你想要的形式:

.Objects[] | select(.ObjectElementName | index("ABC")) | [
    .ObjectElementName,
    ([.ObjectNested | keys_unsorted[] as $k | "\($k):\(.[$k])"] | join(",")),
    .ObjectElementUnit
] | @csv