Skip to main content
 首页 » 编程设计

python之如何为 boto aws sdk 格式化 JSON

2025年05月04日25傻小

我正在使用 boto 和 cloudformation 来编排少量资源

用于创建云形成模板。我正在从我的本地磁盘读取一个 json 文件并创建 json 字符串作为 template_body

的参数传递
try: 
  fileObj = open(filename,'r') 
  json_data = json.loads(fileObj.read()) 
  return json_data 
except IOError as e: 
  print e 
  exit() 

我的云形成连接字符串和堆栈创建是这样的

 cfnConnectObj = cfn.connection.CloudFormationConnection(aws_access_key_id=aKey, aws_secret_access_key=sKey, is_secure=True,debug=2,path='/',validate_certs=True,region=region[3]) #created connection object for cloudformation service 
 
stackID = cfnConnectObj.create_stack('demodrupal',template_body=templateJson, template_url=None,parameters=[],notification_arns=[],disable_rollback=False,timeout_in_minutes=None,capabilities=['CAPABILITY_IAM'],tags=None) 

我收到 Boto 错误 [ERROR]:{"Error":{"Code":"ValidationError","Message":"模板格式错误:JSON 格式不正确。(第 1 行,第 3 列)","类型":"发件人"

为什么会出现这个错误? 我已经使用了 json.loads 但它仍然显示 Json 格式不正确。有什么我想念的吗?

请点亮我

**我是 python 和 boto 的新手

请您参考如下方法:

json.loads 获取 json 并将其转换为 python 对象。如果您已经有一个 JSON 文件,您可以将该文件直接传递给服务。或者,您可以将 JSON 加载到 python 中,在 python 中进行任何调整,然后使用 json.dumps 来获取格式正确的 JSON。