如何使用docker inspect --format从对象获取第一个密钥(获取容器网络名称) [英] How to get first key from object using docker inspect --format (get name of network of container)

查看:134
本文介绍了如何使用docker inspect --format从对象获取第一个密钥(获取容器网络名称)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的命令:

$ docker inspect reacthublh_mysql_1 -f "{{json .NetworkSettings.Networks }}"

为我提取的输出为:

{"reacthublh-network":{"IPAMConfig":null,"Links":null,"Aliases":["1b905711e127","mysql"],"NetworkID":"d2b6bd4815a2eb48a57d05e5d219894f453c15e3f8b5a331a5f0668ed98f4730","EndpointID":"c71240571cc1cfb7bd50119aaf6aaef3dfbc2dc56732e0fd6f593ebe00861edc","Gateway":"172.30.0.1","IPAddress":"172.30.0.2","IPPrefixLen":16,"IPv6Gateway":"","GlobalIPv6Address":"","GlobalIPv6PrefixLen":0,"MacAddress":"02:42:ac:1e:00:02","DriverOpts":null}}

问题是如何仅提取作为json对象第一键的 reacthublh-network

the question is how to extract only reacthublh-network which is first key of json object?

UPDATE :

我现在发现的唯一方法是:

The only way that I found now is:

$ docker inspect reacthublh_mysql_1 -f "{{json .NetworkSettings.Networks }}" | cut -d '"' -f2

可以准确输出我需要的内容,但我很好奇它是否仍然可以在--format参数中完成

which outputs exactly what I need but I'm curious if it's still possible to do it in --format parameter

推荐答案

docker inspect -f 选项使用Go 文本/模板语言,扩展名很少。我认为可以只打印第一个网络名称,但是可以打印出所有网络名称,而不打印其他详细信息。这里的技巧是遍历 Networks 对象作为地图并打印出键:

The docker inspect -f option uses the Go text/template language, with fairly few extensions. I don't think it's directly possible to print only the first network name, but it is possible to print out all of the network names and no other details. The trick here is to iterate over that Networks object as a map and print out the keys:

docker inspect jolly_hodgkin \
  -f '{{range $k, $v := .NetworkSettings.Networks}}{{printf "%s\n" $k}}{{end}}'

如果您具有用于JSON操作的专用命令行工具(例如 jq )查询语言可能更强大,并且更适合您需要的数据操作。 jq 调用以专门获取第一个Docker网络的名称可能看起来像

If you have a purpose-built command-line tool for JSON manipulation (like jq) its query language might be more powerful and more suited for the data manipulation you need. A jq invocation to specifically get the name of the first Docker network might look like

docker inspect jolly_hodgkin \
  | jq -r '.[].NetworkSettings.Networks | keys | first'

这篇关于如何使用docker inspect --format从对象获取第一个密钥(获取容器网络名称)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆