0

Firstly,thank you so much for your support.

I have trouble parsing a json output into csv format. I was able to get some kind of output but that does not meet the expectation.

Curl Command output

{
    "results": [{
            "name": "smith Jones",
            "DOB": "1992-03-26",
            "Enrollmentdate": "2013-08-24"

        },

        {
            "name": "Jacob Mathew",
            "DOB": "1993-03-26",
            "Enrollmentdate": "2014-10-02"
        },

        {
            "name": "Anita Rodrigues",
            "DOB": "1994-03-26",
            "Enrollmentdate": "2015-02-19"
        }
    ]
}

JQ commond used

<curl-command>|jq '.results | map(.name), map(.DOB), map(.Enrollmentdate) | @csv' >file.csv

My Output

smith jones, Jacob Mathew, Anita Rodrigues
1992-03-26, 1993-03-26, 1994-03-26
2013-08-24, 2014-10-02, 2015-02-19 

This might not be csv exactly but below is the expected output.

Name                 DOB             Enrollmentdate
smith jones,       1992-03-26,        2013-08-24
jacob Mathew,      1993-03-26,        2014-10-02
Anitha Rodrigues,  1994-03-26,        2015-02-19

1 Answer 1

2

With your sample JSON, the invocation:

jq -r '
  .results[]
  | [.name, .DOB, .Enrollmentdate ]
  | @csv'

produces:

"smith Jones","1992-03-26","2013-08-24"
"Jacob Mathew","1993-03-26","2014-10-02"
"Anita Rodrigues","1994-03-26","2015-02-19"

If you don't want the (in this case) superfluous quotation marks, you could replace @csv by join(",") but it would be better to write a simple filter to take care of values with commas, etc.

Headers

If the first result has the keys in the correct order, you could get away with:

  (.results[0] | keys_unsorted),
  (.results[]
  | [.name, .DOB, .Enrollmentdate ])
  | @csv

But it would probably be better to use a bit of jq magic along the lines of the following:

  (.results[0] | keys_unsorted) as $headers
  | $headers,
    (.results[]
     | [getpath($headers[]|[.])])
  | @csv
Sign up to request clarification or add additional context in comments.

1 Comment

Thank You! this worked like a charm :) but how do i print the key names(name, DOB, Enrollmentdate)? I can write a bash script to generate it but was wondering if JQ could solve it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.