american-ninja-warrior
american-ninja-warrior

Reputation: 8215

Wrap Bash/Unix line oriented pipe in a json structure

How can I convert this

http://www.google.co.uk
http://www.reddit.com
http://www.ebay.com

to this using jq if possible:

{ "listing": "http://www.google.co.uk" }
{ "listing": "http://www.reddit.com" }
{ "listing": "http://www.ebay.com" }

What I tried:

$ echo "    http://www.google.co.uk
>     http://www.reddit.com
>     http://www.ebay.com"  |  jq --slurp --raw-input 'split("\n")[:-1] | map({ listing: .})'
[
  {
    "listing": "    http://www.google.co.uk"
  },
  {
    "listing": "    http://www.reddit.com"
  },
  {
    "listing": "    http://www.ebay.com"
  }
]

Braces and stuff cannot be in a line of its own, because I'm doing "line oriented processing" where each line represents a "row" of data.

Upvotes: 1

Views: 110

Answers (2)

peak
peak

Reputation: 116870

This should do it:

jq -cR '{listing: .}'

This assumes there are no superfluous spaces at the beginning of the input lines. If leading and trailing spaces are to be removed, you could use this composite filter:

sub("^ +";"") | sub(" +$";"")

Upvotes: 2

steffen
steffen

Reputation: 17018

Create objects for each input line:

echo -e "l1\nl2\nl3" | jq -c -R '{"listing": .}'

Output:

{"listing":"l1"}
{"listing":"l2"}
{"listing":"l3"}

Upvotes: 2

Related Questions