jsonjqnested-json

How to print optional arrays in JQ


I have the following example:

{
    "field1": "test1",
    "array1": [
        {
            "field2": "test20",
            "array2": [
                {
                    "field3": "test30",
                    "array3": [
                        "11","12"
                    ]
                }
            ]
        },
        {
            "field2": "test21",
            "array2": [
                {
                    "field3": "test31",
                    "array3": [
                    ]
                }
            ]
        },
        {
            "field2": "test22",
            "array2": [
                {
                    "field3": "test32"
                }
            ]
        }
    ]
}

I would like to get the following:

{"field1":"test1","field2":"test20","field3":"test30","array3":"11"}
{"field1":"test1","field2":"test20","field3":"test30","array3":"12"}
{"field1":"test1","field2":"test21","field3":"test31","array3":null}
{"field1":"test1","field2":"test22","field3":"test32","array3":null}

I am currently stuck at:

jq --compact-output '.field1 as $field1 | .array1[] | . | .field2 as $field2 | . | .array2[] | . | .field3 as $field3 | try ({$field1, $field2, $field3, array3: .array3[]}) catch ({$field1, $field2, $field3, array3: null})'

which prints out 3 of the 4 rows, but I lose line 3. Any suggestions?


Solution

  • This works with your example input:

    {field1} + (.array1[] |
      {field2} + (.array2[] |
        {field3} + (
          if has("array3") and (.array3 | length) > 0 then
            {array3: .array3[]}
          else
            {array3: null}
          end
        )
      )
    )
    

    Online demo