Guidelines

This site is for tech Q&A. Please keep your posts focused on the subject at hand.

Ask one question at a time. Don't conflate multiple problems into a single question.

Make sure to include all relevant information in your posts. Try to avoid linking to external sites.

Links to documentation are fine, but in addition you should also quote the relevant parts in your posts.

0 votes
191 views
191 views

I want to check if all Docker containers on a host are in "running" state. My naive approach was to print JSON output and then process that with jq:

docker ps -a --format json | jq -r 'map(.State=="running")|all'

However, docker ps apparently produces individual JSON objects per container, not an array of JSON objects, so the above produces the following errors:

jq: error (at :1): Cannot index string with string "State"
jq: error (at :2): Cannot index string with string "State"
...

How can I make docker ps produce a proper JSON array?

in Sysadmin
by (115)
2 18 33
edit history

Please log in or register to answer this question.

1 Answer

0 votes
 

AFAIK the docker command doesn't support this and will always output individual objects. But you can tell jq to ingest a series of input objects into an array before processing them:

... | jq -sr 'map(.State=="running")|all'

From the documentation:

  • --slurp/-s:
    Instead of running the filter for each JSON object in the input, read the entire input stream into a large array and run the filter just once.
by (115)
2 18 33
edit history
...