skip to Main Content

Working with a nested arrays like this:

[
    {
        "value1": "Data1-0",
        "value2": "Data2-0",
        "nArray": [
            {"nValue1": "nData1-0a","nValue2": "nData2-0a"},
            {"nValue1": "nData1-0b","nValue2": "nData2-0a"},
            {"nValue1": "nData1-0c","nValue2": "nData2-0a"}
        ],
        "value3": "Data3-0"
    },
    {
        "value1": "Data1-1",
        "value2": "Data2-1",
        "nArray": [
            {"nValue1": "nData1-1a","nValue2": "nData2-1a"},
            {"nValue1": "nData1-1b","nValue2": "nData2-1a"}
        ],
        "value3": "Data3-1"
    }
]

Desired output is CSV format like this:

Value1,Value2,nArrayCount
Data1-0,Data2-0,Data3-0,3
Data1-1,Data2-1,Data3-1,2

I was able to get the nested values but that produces multiple rows for each nArray value with this:

[.[] | [.value1,.value2,.value3] + (.nArray[]? | [.nValue1]) ] | .[] | @csv

All I need is a count.

2

Answers


  1. Close enough. Use length to get the length of an array.

    $ jq -r '
    ["Value1", "Value2", "count"],
    (.[] | [.value1, .value2, (.nArray|length)])
    | @csv' input.json
    "Value1","Value2","count"
    "Data1-0","Data2-0",3
    "Data1-1","Data2-1",2
    $ jq -r '
    ["Value1", "Value2", "count"],
    (.[] | [.value1, .value2] + [.nArray|length])
    | @csv' input.json
    "Value1","Value2","count"
    "Data1-0","Data2-0",3
    "Data1-1","Data2-1",2
    
    Login or Signup to reply.
  2. If the data is like the one in your post (no double quotes or comma in Values), then :

    #!/usr/bin/env bash
        
    jq -r '["Value1", "Value2", "Value3", "nArrayCount"],
           (.[] | [.value1, .value2, .value3, (.nArray|length)])
           | join(",")' input.json
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search