2

I am getting Json as column ID and arrays -

  {
      "ObjectID": [
        0,
        1,
        2,
        3,
        4
      ],
      "Name": [
        "Apple",
        "Orange",
        "Grape",
        "Banana",
        "Jackfruit"
      ],
      "Color": [
        "Red",
        "Orange",
        "Green",
        "Yellow",
        "null"
      ],
      "Acidity": [
        3.9,
        3.5,
        2.99,
        6,
        5.0
      ]
    }

I am trying to convert it using jq to to a plain CSV format like -

ObjectID,Name,Color,Acidity
0,Apple,Red,3.9
1,Orange,Orange,3.5
2,Grape,Green,2.99
3,Banana,Yellow,6
4,Jackfruit,null,5.0

Question related to Export JSON to CSV with Headers using JQ . Looking for preferably a generic answer.

2 Answers 2

2

Answering my own question after playing with given answers, generic solution for json arrays

jq --raw-output 'to_entries|map(.key),(map(.value)|transpose[])|@csv'   
1

A solution using the transpose function:

<file jq -r '(to_entries|map(.key)),([.ObjectID,.Name,.Color,.Acidity]|transpose|.[])|@csv'

The object name is extracted using to_entries|map(.key).

The object content is put inside an array and transposed in order to get arrays with element of each object.

The result is then going through the @csv operator that converts the array into a comma separated string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.