Home > Software engineering >  Transforming arrays of varying length into objects based on the parity of their indices in JQ
Transforming arrays of varying length into objects based on the parity of their indices in JQ

Time:09-08

Basically i need to transform a set of arrays depending on if the index is odd or even, while the length of each array is different. What i have been unable to do is to transform and add the additional arrays into the right children array, which im guessing should be done based on if the index of the array is odd or even. I need a universal solution, which would work on a bigger amount of data also.

json example:

[
  [
    [
      "dev",
      5
    ],
    [
      [
        "RT",
        1
      ],
      [
        "CP",
        2
      ]
    ]
  ],
  [
    [
      "jez",
      2
    ],
    [
      [
        "ME",
        1
      ],
      [
        "PW",
        1
      ]
    ],
    [
      "lem",
      3
    ],
    [
      [
        "AR",
        1
      ],
      [
        "ME",
        2
      ]
    ],
    [
      "has",
      1
    ],
    [
      [
        "MOBILE",
        1
      ]
    ]
  ]
]

transform into:

{
  "children": [
    {
      "name": "dev",
      "value": 5,
      "children": [
        {
          "name": "RT",
          "value": 1
        },
        {
          "name": "CP",
          "value": 2
        }
      ]
    }
  ]
}
{
  "children": [
    {
      "name": "jez",
      "value": 2,
      "children": [
        {
          "name": "ME",
          "value": 1
        },
        {
          "name": "PW",
          "value": 1
        }
      ]
    },
    {
      "name": "lem",
      "value": 3,
      "children": [
        {
          "name": "AR",
          "value": 1
        },
        {
          "name": "ME",
          "value": 2
        }
      ]
    },
    {
      "name": "has",
      "value": 1,
      "children": [
        {
          "name": "MOBILE",
          "value": 1
        }
      ]
    }
  ]
}

what i have been able to transform it into(jqplay: https://jqplay.org/s/7nZEbfRTKDz)

{
  "children": [
    {
      "name": "dev",
      "value": 5,
      "children": [
        {
          "name": "RT",
          "value": 1
        },
        {
          "name": "CP",
          "value": 2
        }
      ]
    }
  ]
}
{
  "children": [
    {
      "name": "jez",
      "value": 2,
      "children": [
        {
          "name": "ME",
          "value": 1
        },
        {
          "name": "PW",
          "value": 1
        }
      ]
    }
  ]
}

thanks in advance for any answers

CodePudding user response:

This should work if your actual data doesn't contain deeper arrays than in your example:

def f: {
  name: .[0],
  value: .[1]
};
{
  children: [
    _nwise(2) | (.[0] | f)   {
      children: (.[1] | map(f))
    }
  ]
}

Online demo

  • Related