6

I am trying to convert a json structure that key1: array of values, key2: array of values ,.... to an array of objects. The size of arrays is same and each object is just aggregate of items at position x in each array. Need help converting this preferably with generic code with jq.

Input

{
  "IdentifierName": [
    "A",
    "B",
    "C"
  ],
  "Code": [
    5,
    8,
    19
  ]
}

Expected Output

[
  {
    "IdentifierName": "A",
    "Code": 5
  },
  {
    "IdentifierName": "B",
    "Code": 8
  },
  {
    "IdentifierName": "C",
    "Code": 19
  }
]

Edit: progress so far:

jq 'to_entries|map(.key) as $keys| (map(.value)|transpose) as $values |$values|map($keys, .)'

The last step is to somehow index with the keys into the values that I am still unable to get right.

2 Answers 2

6

Answering my own question:

jq 'to_entries|map(.key) as $keys| (map(.value)|transpose) as $values |$values|map([$keys, .] | transpose| map( {(.[0]): .[1]} ) | add)'

Explanation: Extract keys ["IdentifierName", "Code"] and values as [ [ "A", 5 ], [ "B", 8 ], [ "C", 19 ] ]
Then to index from keys to values, take json-seq of key-tuple with (each) value tuple and transpose and zip them in pairs.

 echo '[[
    "IdentifierName",
    "Code"
  ],
  [
    "C",
    19
  ]
]'|jq '.|transpose| map( {(.[0]): .[1]} ) | add'

Combining both gives solution. This will work for any number of elements (0 and 1 are just key and value, not first and second).

2
$ jq '[.IdentifierName, .Code] | transpose | map( { "IdentifierName": .[0], "Code": .[1] } ) ' file.json
[
  {
    "IdentifierName": "A",
    "Code": 5
  },
  {
    "IdentifierName": "B",
    "Code": 8
  },
  {
    "IdentifierName": "C",
    "Code": 19
  }
]

I'm extracting the two arrays into an array (of two arrays) that I transpose. For the given data, this produces [["A",5],["B",8],["C",19]]. I then map each individual element of this array to an object with the wanted keys.

This could possibly be made neater somehow. For example, it would be nice to not have to reconstruct the objects at the end with explicit key names, and it would also be nice if one could generalize this to n sub-arrays, not just two.

1
  • This is helpful, am I still trying for a generic answer.
    – asterisk
    May 26, 2020 at 19:01

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .