【问题标题】:How to organize an array that is returned using Curl?如何组织使用 Curl 返回的数组?
【发布时间】:2016-10-14 11:15:24
【问题描述】:

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

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"

【问题讨论】:

    标签: python linux bash curl sh


    【解决方案1】:

    你应该考虑看看jq,玩起来真的很有趣:

    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

    【讨论】:

    • 我公司的笔记本电脑上好像没有安装jq,我没有安装它的权限-bash: jq: command not found
    • @meallhour 如果需要,您可以下载独立的二进制文件。然而,我会说 Python 是一个不错的选择。 stedolan.github.io/jq/download
    猜你喜欢
    • 2021-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-10
    • 1970-01-01
    • 2016-09-23
    相关资源
    最近更新 更多