0

I know this is possible with jq, but there is an added complexity. One of the fields inside the json object is an array of strings. How do we handle this with jq?

{ "var": 1, "section": ["1","2","3"], "x": "test1" }, { "var": 2, "section": ["2","3","4"], "x": "test2" }, { "var": 3, "section": ["3","4","5"], "x": "test3" }, 

How do we make CSV output like this?

var,section,x "1","[1,2,3]","test1" "2","[2,3,4]","test2" "3","[3,4,5]","test3" 

I'm thingking of using JSON.stringify inside the jq arguments.

1 Answer 1

3

With the caveat that you have to be careful what you wish for, and assuming the input is an array of objects as shown:

.[] | [.[] | if type == "array" then map(tonumber? // .) else . end | tostring] | @csv 

produces the desired output, except for the header row.

(The "tonumber? // ." avoids an error if the array contents cannot be converted to a number.)

Generalization

Here's a variant that (a) produces a row of headers for all the keys in the first object, whatever they may be; and (b) is robust with respect to re-ordering the keys within the objects:

. as $in | ($in[0] | keys_unsorted) as $h | ($h, ( $in[] | ( [range(0; $h|length) as $i | getpath( [$h[$i]] )] | map(if type == "array" then map(tonumber? // .) else . end) | map(tostring) ) )) | @csv

With this in tocsv.jq and your input in input.json:

$ jq -r -f tocsv.jq input.json "var","section","x" "1","[""a"",2,3]","test1" "2","[2,3,4]","test2" "3","[3,4,5]","test3"

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.