You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python3处理Docker API容器数据:提取指定键值及修复遍历错误

解决Docker API JSON数据提取问题&递归遍历报错修复

首先,先帮你搞定那个递归代码的报错问题——你遇到的AttributeError: 'list' object has no attribute 'items',是因为Docker API返回的容器列表最外层是一个数组(list),而你的递归函数只处理了字典(dict)类型,没考虑列表的情况,直接把整个data传进去自然就炸了。

一、先搞定核心需求:提取匹配容器的Id和Names

Docker API的GET /containers/json返回的结构是容器对象组成的数组,所以第一步要先遍历这个数组里的每个容器对象,再做匹配和提取。

举个例子,假设你要匹配Names里包含"my-app"的容器,代码可以这么写:

import json

with open('test.json') as json_file:
    containers = json.load(json_file)  # 这里containers是list类型,每个元素是一个容器dict

# 定义你要匹配的特定字符串
target_str = "my-app"

# 遍历每个容器,提取符合条件的Id和Names
matched_containers = []
for container in containers:
    # 注意Names是list格式,比如["/my-app-1"],用any判断是否包含目标字符串
    if any(target_str in name for name in container['Names']):
        matched_containers.append({
            'Id': container['Id'],
            'Names': container['Names']
        })

# 打印前两个匹配的容器(如果存在的话)
for idx, item in enumerate(matched_containers[:2]):
    print(f"容器 {idx+1}:")
    print(f"  Id: {item['Id']}")
    print(f"  Names: {item['Names']}")

二、获取深层的PrivatePort值

PrivatePort藏在容器对象的NetworkSettings->Ports下面,这个结构是字典:键是端口格式(比如"80/tcp"),值是包含端口信息的列表。提取代码可以这么写:

for container in containers:
    # 用get方法避免键不存在引发报错
    network_settings = container.get('NetworkSettings', {})
    ports = network_settings.get('Ports', {})
    
    print(f"容器 {container['Id'][:12]} 的PrivatePort:")
    for port_key, port_info_list in ports.items():
        if port_info_list:  # 有些端口可能未映射,值为None,需要过滤
            for port_info in port_info_list:
                print(f"  {port_key}: {port_info['PrivatePort']}")

三、修正递归遍历函数,支持list和dict嵌套

原来的递归函数只处理了dict类型,现在我们修改它,让它能同时处理list和dict的嵌套结构:

import json

def recursive_items(data):
    if isinstance(data, dict):
        for key, value in data.items():
            yield (key, value)
            yield from recursive_items(value)
    elif isinstance(data, list):
        for item in data:
            yield from recursive_items(item)
    else:
        # 基本类型(字符串、数字等)返回None作为键,也可以根据需求调整输出逻辑
        yield (None, data)

with open('test.json') as json_file:
    data = json.load(json_file)

for key, value in recursive_items(data):
    # 过滤掉list元素对应的无键情况
    if key is not None:
        print(key, value)

现在这个函数就能正确遍历Docker返回的JSON结构了,不管是外层的容器列表,还是里面嵌套的各种字典和数组。

内容的提问来源于stack exchange,提问作者user14460469

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:24:48