JQ looks like a great tool, but I'm struggling with it. Here is what I am trying to do:
Extract just the values from this chef knife search and generate a CSV.
given this command and output:
knife search node "name:foo*" -a name -a cpu.total -a memory.total -Fj
{ "results": 2, "rows": [ { "foo-01": { "name": "foo-01", "cpu.total": 12, "memory.total": "16267368kB" } }, { "foo-02": { "name": "foo-02", "cpu.total": 12, "memory.total": "16264296kB" } } ] }
I would like to get the values extracted to CSV like this:
foo-01,12,16267368kB foo-02,12,16264296kB
(I can deal with the quotes)
Best Answer
This:
.rows
into the output stream (.rows.[]
).|
)..[]
)..name
,.["cpu.total"]
, and.["memory.total"]
each evaluated on that object (.[ .name, ... ]
).map(tostring)
).join(",")
).jq -r
outputs raw data, rather than quoting and escaping it. The output is then:as you wanted. Depending on your CSV parser & the real data, you might need extra quoting around the strings, which you can add in, or use
@csv
in place of the last two steps.We could skip the
map
by converting only the one value inside, which takes some extra brackets:And probably the ugliest alternative:
In this case, we don't rely on the
.name
field, and build up the whole string manually. If you need a highly customised format, this is the most flexible option.