Search code examples
jsonexport-to-csvjq

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


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

Question is an extension of previous solution:

Use JQ to parse JSON array of objects, using select to match specified key-value in the object element, then convert to CSV


Data Source:

{
  "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 command to extract [FAILS]

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

Output CSV required (or variation, so long as ObjectNested appears into a single column in CSV)

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

Solution

  • With keys_unsorted and string interpolation, it's easy to turn ObjectNested into the form you desired:

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