When I issue the following command
docker ps --no-trunc --format '{"name":"{{.Names}}", "status":"{{.Status}}"}'
I get output such as:
{"name": "container1", "status": "Up 10 hours"}
{"name": "container2", "status": "Up 10 hours"}
Each of these line is a valid JSON object, but I am lazy and want the whole output to be a valid JSON which represents a list of dictionaries:
[
{"name": "container1", "status": "Up 10 hours"},
{"name": "container2", "status": "Up 10 hours"}
]
Is there a way for the docker ps
command to output in that format?
CodePudding user response:
Simplest thing would be to pipe to jq -s
:
docker ps --no-trunc --format '{"name":"{{.Names}}", "status":"{{.Status}}"}' \
| jq -s
From jq --help
:
-s read (slurp) all inputs into an array; apply filter to it;
PS: If you are going to use jq
anyways, then I suggest the following command instead:
docker ps --no-trunc --format '{{ json . }}' \
| jq -s 'map({name:.Names,status:.Status})'
The command is leaving the json serialization to the Go template function json
instead of doing it manually as in your example. This has the benefit that problematic characters in container names, for example unicode, wouldn't break the json output.