2

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?

2
  • Is .a constant or it could change/dynamic ? Commented Dec 15, 2020 at 16:46
  • a is constant, not changing. Commented Dec 15, 2020 at 17:46

2 Answers 2

4

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"
  ]
}
Sign up to request clarification or add additional context in comments.

4 Comments

inputs.a won't work if I'm not mistaken, inputs is an array and you can't access its properties. [inputs | map(.a)] would work just fine though
@Aaron it's not. inputs is a stream, OP just forgot .a.
My bad, I had tested from my own sample and left the --slurp, which made inputs empty and raised an error that could be interpreted as trying to index an array with a field
np, I wouldn't have assumed so.
1

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.

2 Comments

The -s option is a relic of the days of yore when jq did not have input and inputs. When the goal is to illustrate or encourage best practices, its use should generally be avoided when possible except to highlight its inefficiency.
@peak thanks for your feedback, I felt using slurp mode made for simpler code and I wasn't aware of its inefficiency. I guess I'll have to get used to input[s]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.