0

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"

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.