meallhour meallhour - 5 months ago 30
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 http://internal.private.registry.com/v2/_catalog | python -c 'import sys,json;data=json.loads(sys.stdin.read()); 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

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"

Breakdown:

.                 # 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

Comments