Isaac
Isaac

Reputation: 840

Join multiple JSON objects into an array

I have a command that outputs multiple simple json objects like this (for development purposes previously piped to a file foo.txt):

$ cat foo.txt
{"a": "b"}
{"a": "e"}
{"a": "f"}

Now I would like to get it formatted like this:

{
  "a": ["b", "e", "f"]
}

I am pretty sure it can be done with jq, but all I can get is the following:

$ cat foo.txt |jq -n '.a |= [inputs]'
{
  "a": [
    {
      "a": "b"
    },
    {
      "a": "e"
    },
    {
      "a": "f"
    }
  ]
}

Any hints?

Upvotes: 2

Views: 2583

Answers (2)

Aaron
Aaron

Reputation: 24812

I would use the following :

jq --slurp --compact-output '{ a: map(.a) }' foo.txt

--slurp makes jq read a sequence of JSON objects as an array of those objects. We map this array of objects to an array of the values of their .a field, and finally return an object which holds this array as its .a field.

You can try it here.

Upvotes: 1

oguz ismail
oguz ismail

Reputation: 50805

You were really close. JQ won't extract .a from input objects unless you explicitly state that.

$ jq -n '.a = [inputs.a]' foo.txt
{
  "a": [
    "b",
    "e",
    "f"
  ]
}

Upvotes: 4

Related Questions