meallhour meallhour - 1 year ago 108
Linux Question

How to organize an array that is returned using Curl?

I am using the following command to list all the images in a catalog:

curl -s | python -c 'import sys,json;data=json.loads(; print data["repositories"]'

It is giving the following output:

[u'centos', u'containersol/consul-server', u'containersol/mesos-agent', u'containersol/mesos-master']

How to organize the output in the following form:

Repo1: "centos"
Repo2: "containersol/consul-server"

Answer Source

You should consider taking a look at jq it's really quite fun to play with:

curl -s ... | jq -r '.repositories[0:2] | to_entries | map("Repo \(.key+1 | tostring): \"\(.value)\"")[]'
Repo1: "centos"
Repo2: "containersol/consul-server"


.                 # Read stdin
repositories[0:2] # Take the first two from repositories array
| to_entries      # Convert to an array of object with key, value pairs:
                  # [ {"key": 0, "value": "..."}, {key: 1, "value": "..."} ]
| map("Repo"      # Map array
     + (.key+1 | tostring)
     + ": \""     # Literal : and "
     + .value
     + "\"")      # Literal "
[]                # Convert array to a newline separated list

-r prints output that are not JSON encoded, eg: "abc" -> abc

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download