如何组织使用Curl返回的数组?

2024-05-20 19:35:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用以下命令列出目录中的所有图像:

curl -s http://internal.private.registry.com/v2/_catalog | python -c 'import sys,json;data=json.loads(sys.stdin.read()); print data["repositories"]'

它提供以下输出:

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

如何按以下形式组织输出:

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

Tags: 图像命令目录jsonhttpdataserversys
1条回答
网友
1楼 · 发布于 2024-05-20 19:35:47

你应该考虑看看^{}玩起来真的很有趣:

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打印非JSON编码的输出,例如:"abc"->;abc

相关问题 更多 >