4 ms·
"cobbled-together" jq as it often appears in the wild will often compare badly with crafted solutions because the writer's goal is usually GSD and not write pre
by preferjq 4y ago
"cobbled-together" jq as it often appears in the wild will
often compare badly with crafted solutions because the writer's
goal is usually GSD and not write pretty code.
People with the time and inclination to slow down and think a
little more about how the tools work will produce cleaner solutions.
In your example to convert
{"name":"foo","vals":[1,2,3]}
to
{"name":"foo","val":1}
{"name":"foo","val":2}
{"name":"foo","val":3}
All you need is this jq filter
{name:.name, val:.vals[]}
To me this is much better than the proposed zq or jq solution you're using as a basis
for comparison. You could almost use the shorter
.vals = .vals[]
if the name in the output didn't change.
These filters takes advantage of how jq's [] operator converts a single
result into separate results. For people new to jq this behavior is often
confusing unless they've seen things like Cartesian products.
.[] - https://stedolan.github.io/jq/manual/#Array/ObjectValueIterator%3A.%5B%5D https://stedolan.github.io/jq/manual/#Array/ObjectValueItera...
- hyperpallium2 4y agocan also use name instead of name:.name I think jq is very elegant - genius even - but whenever I use it, I have to look up the docs for syntax. But I guess that's true for any infrequently used tool.
- chris37879 4y agoThis exactly. I think JQ's problem in this regard is further compounded because its query language just doesn't feel like anything else most people have used, I've certainly never come across anything quite like it, anyway.
- MarkMarine 4y agocounter point: I reach for jq probably twice a year. It's a slog every time, but way way less work than diving into the terse syntax and understanding the inner workings of jq. A good abstraction is the border of my understanding, a leaky abstraction means I have to have mastery of the internals to be successful. jq is a leaky abstraction.