Not quite getting it. I can produce multiple lines but cannot get multiple entries to combine. Looking to take Source JSON and output to CSV as shown:
Source JSON:
[{"State": "NewYork","Drivers": [
{"Car": "Jetta","Users": [{"Name": "Steve","Details": {"Location": "Home","Time": "9a-7p"}}]},
{"Car": "Jetta","Users": [{"Name": "Roger","Details": {"Location": "Office","Time": "3p-6p"}}]},
{"Car": "Ford","Users": [{"Name": "John","Details": {"Location": "Home","Time": "12p-5p"}}]}
]}]
Desired CSV:
"NewYork","Jetta","Steve;Roger","Home;Office","9a-7p;3p-6p"
"NewYork","Ford","John","Home","12p-5p"
JQ code that does not work:
.[] | .Drivers[] | .Car as $car |
.Users[] |
[$car, .Name] | @csv
3
Answers
Not quite optimised, but I though’t I’d share the general idea:
map()
over each state, remember the name (map(.State as $s |
)group_by(.Car)
@csv
map()
andjoin()
to create the fields forName
,Location
andTime
This part could be improved so you don’t need that duplicated part
Output (with
--raw-output
:JqPlay seems down, so I’m still searching for an other way of sharing a public demo
You’re looking for something like this:
Far from perfect, but it builds the result incrementally so it should be easily debuggable and extensible: