How can I use jq to separate pairs of values with a delimiter?

0
0
Asked By TechWhiz99 On

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

Answered By InsightfulCoder On

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.

Answered By ScriptMaster007 On

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.

LogicLover88 -

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

SyntaxSavant -

Absolutely! Your example eliminates the need for `cat`, which isn't needed here at all.

Answered By CodeGuru123 On

You might want to try `jq -r -c '.[] | "(.name),(.argument)"'`. This should give you the formatting you're looking for!

DataNinja456 -

If you need a custom delimiter, you can wrap it in an array and use `join`. For example: `jq -r '[.[] | "(.name),(.argument)"] | join("")'`.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.