一、前言
最近想自己手动写一个基于DockerAPI的远程管理工具,本系列文章将一直记录编写过程中遇到的问题及解决方法
相关链接:
二、面临的问题
2.1、API数据混乱
一开始我写的代码是这样的
import json
import requests
url = 'http://1.1.1.11:2375/containers/json?all=1'
r = requests.get(url)
decoded = json.dumps(r.text)
print(decoded)
执行结果是这样的
而我希望得到的数据是这样的
root@ubuntu20:~# curl http://1.1.1.11:2375/containers/json | python3 -m json.tool
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 1194 100 1194 0 0 1166k 0 --:--:-- --:--:-- --:--:-- 1166k
[
{
"Id": "f8026170e99a16c5a3aa4da1a80f7c66babcc0b3652b507dd44efe0f8125388e",
"Names": [
"/cool_kalam"
],
"Image": "centos",
"ImageID": "sha256:470671670cac686c7cf0081e0b37da2e9f4f768ddc5f6a26102ccd1c6954c1ee",
"Command": "/bin/bash",
"Created": 1593242626,
"Ports": [],
"Labels": {
"org.label-schema.build-date": "20200114",
"org.label-schema.license": "GPLv2",
"org.label-schema.name": "CentOS Base Image",
"org.label-schema.schema-version": "1.0",
"org.label-schema.vendor": "CentOS",
"org.opencontainers.image.created": "2020-01-14 00:00:00-08:00",
"org.opencontainers.image.licenses": "GPL-2.0-only",
"org.opencontainers.image.title": "CentOS Base Image",
"org.opencontainers.image.vendor": "CentOS"
},
"State": "running",
"Status": "Up 12 minutes",
"HostConfig": {
"NetworkMode": "default"
},
"NetworkSettings": {
"Networks": {
"bridge": {
"IPAMConfig": null,
"Links": null,
"Aliases": null,
"NetworkID": "fe0b15e170623843c6ddaca8103cee0071aba3c18cc8f02cc14a19847f7ecca4",
"EndpointID": "0c06037c7b2b4bf4957f02906d3764f0dbfbcea9cc2423385b7eea94d2c7a504",
"Gateway": "172.17.0.1",
"IPAddress": "172.17.0.2",
"IPPrefixLen": 16,
"IPv6Gateway": "",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"MacAddress": "02:42:ac:11:00:02",
"DriverOpts": null
}
}
},
"Mounts": []
}
]
三、解决方法
其实只需要把text改成json即可
import json
import requests
url = 'http://1.1.1.11:2375/containers/json?all=1'
r = requests.get(url)
decoded = json.dumps(r.json(), indent=4)
print(decoded)
然后得到的结果是这样的
下一篇写如何从json数据里面取得自己想要的数据
本文来自博客园,作者:坐公交也用券,转载请注明原文链接:https://www.cnblogs.com/liumou-site/p/17106059.html