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

使用Boto3获取AWS组织子账户列表时遇JSON序列化错误求助

问题解决:Boto3获取AWS组织子账户时的JSON序列化错误

错误原因

你直接对Boto3返回的PageIterator对象执行json.dumps(),但该对象是迭代器类型,并非原生可JSON序列化的数据结构(如字典、列表),因此触发了TypeError。

修复后的代码

需要遍历分页迭代器,提取所有账户数据后再进行JSON序列化:

import boto3
import json

client = boto3.client('organizations')
paginator = client.get_paginator('list_accounts_for_parent')

# 替换为实际的ParentId(如OU的ID,格式为ou-xxxx-xxxx)
response_iterator = paginator.paginate(
    ParentId='ou-xxxx-xxxx',
    PaginationConfig={
        'MaxItems': 123,
        'PageSize': 123
        # 无起始token时可移除StartingToken参数
    }
)

# 遍历迭代器收集所有账户数据
all_accounts = []
for page in response_iterator:
    all_accounts.extend(page['Accounts'])

# 序列化并打印结果
print(json.dumps(all_accounts, indent=2))

额外注意事项

  • ParentId必须是AWS组织中合法的父节点ID(如组织单元OU的ID或根节点IDr-xxxx),不能留空。
  • 若无需指定起始分页标记,可从PaginationConfig中移除StartingToken参数,Boto3会自动处理分页逻辑。
  • 执行代码的IAM身份必须拥有organizations:ListAccountsForParent权限,否则会触发权限错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 09:01:01