Hey everyone! I'm looking for some help with jq. I want to format data such that pairs of values are separated by a specific delimiter. For example, I'd like to convert this JSON:
`[`
`{`
`"name": "1",`
`"argument": "a"`
`},`
`{`
`"name": "2",`
`"argument": "b"`
`}`
`]`
into outputs like `1,a;2,b` or `1,a`
`2,b`.
Currently, I'm using this command: `cat file.txt | jq -r -c 'map(.name, .argument) | join (";")'` which gives me `1;a;2;b`. Without the "join" command, it turns out as `["1","a","2","b"]`. So it seems jq is treating the input as a single array. Any tips on how to achieve the desired formatting?
3 Answers
So, the reason `map(.name, .argument)` isn't giving you the desired result is that it's flattening the outputs. Instead, you could use `map([.name, .argument] | join(",")) | join(";")` to keep it organized. This way, you join each pair into a string, and then you join all those strings together in the final output. It's a more structured approach, especially if the number of arguments might change.
You can achieve that by using this command: `jq -r '[.[] | [ .name, .argument ] | join(",") ] | join(";")'`. It works perfectly to format the output just how you want it! Watch out for unnecessary commands like `cat` though; they just clutter the command.
Absolutely! Your example eliminates the need for `cat`, which isn't needed here at all.
You might want to try `jq -r -c '.[] | "(.name),(.argument)"'`. This should give you the formatting you're looking for!
If you need a custom delimiter, you can wrap it in an array and use `join`. For example: `jq -r '[.[] | "(.name),(.argument)"] | join("

That makes sense! Using `[.[]|f]` can be simpler and cleaner than `map(f)`, right?