将boto3输出保存为JSON

时间:2018-04-12 10:47:48

标签: python json boto3

需要将boto3输出(作为备份)保存到JSON文件

#!/bin/python

import boto3
import json

client = boto3.client('iam')
response = client.get_account_authorization_details(

)

sys.stdout = open('output.json','wt')

print response

我得到了输出:

{u'RoleDetailList': [{u'AssumeRolePolicyDocument': {u'Version': u

我如何摆脱u

并且我无法解析此输出:

with open('output.json') as file:
        data = json.load(file)


    ValueError: Expecting property name: line 1 column 2 (char 1)

尝试:

with open('output.json', 'w') as outfile:
    json.dump(response, outfile)

现在获得:TypeError: datetime.datetime(2016, 8, 20, 13, 51, 7, tzinfo=tzlocal()) is not JSON serializable

2 个答案:

答案 0 :(得分:0)

这是你用最简单的基本方式正确地做到这一点

import boto3
import json

client = boto3.client('ec2')

resp = client.describe_regions()

{u'Regions': [{u'Endpoint': 'ec2.ap-south-1.amazonaws.com',
   u'RegionName': 'ap-south-1'},
  {u'Endpoint': 'ec2.eu-west-3.amazonaws.com', u'RegionName': 'eu-west-3'},
  {u'Endpoint': 'ec2.eu-west-2.amazonaws.com', u'RegionName': 'eu-west-2'},
  {u'Endpoint': 'ec2.eu-west-1.amazonaws.com', u'RegionName': 'eu-west-1'},
  {u'Endpoint': 'ec2.ap-northeast-2.amazonaws.com',
....

with open('random.json', 'w') as fout:
    json.dump(resp, fout)


c = json.load(open('random.json', 'r'))

{u'Regions': [{u'Endpoint': u'ec2.ap-south-1.amazonaws.com',
   u'RegionName': u'ap-south-1'},
  {u'Endpoint': u'ec2.eu-west-3.amazonaws.com', u'RegionName': u'eu-west-3'},
  {u'Endpoint': u'ec2.eu-west-2.amazonaws.com', u'RegionName': u'eu-west-2'},
  {u'Endpoint': u'ec2.eu-west-1.amazonaws.com', u'RegionName': u'eu-west-1'},
  {u'Endpoint': u'ec2.ap-northeast-2.amazonaws.com',
...

答案 1 :(得分:0)

这解决了我的问题,谢谢大家:

#!/bin/python

import boto3
import json
from bson import json_util

client = boto3.client('iam')

response = client.get_account_authorization_details(

)

with open('output.json', 'w') as outfile:
    json.dump(response, outfile, default=json_util.default)