Python从FOR循环输出到有效的JSON

时间:2017-08-08 10:05:21

标签: python json loops boto3

好的伙计们,我是Python的新手。

我已经开始在工作中使用它来使用Boto3

查询AWS

我的第一个任务是构建一个脚本,通过MFA查询AWS中的用户,初始脚本可以正常运行并返回所有没有MFA设备的用户,非常简单。

我想要做的是将列表导出到JSON文件,然后我可以使用Angular应用程序中的数据来显示报告。

当我运行代码时,我得到一个JSON输出但它不正确,它缺少逗号并在每个对象之后关闭JSON而不是创建完整的单一JSON输出。

我的代码如下:

import json
# boto code here

for user in iam.list_users()['Users']:
    mfa = iam.list_mfa_devices(UserName=user['UserName'])
    if len(mfa['MFADevices']) == 0:
        q = []

        q.append({"account": item['alias'], "Username": 
user['UserName'], "MFA": "No MFA Enabled"})
        print json.dumps(q, indent=4)

结果格式为:

[
  {
    "Username": "Username", 
    "MFA": "No MFA Enabled", 
    "account": "account"
  }
]
[
  {
    "Username": "Username", 
    "MFA": "No MFA Enabled", 
    "account": "account"
  }
]

2 个答案:

答案 0 :(得分:1)

有许多有效的JSON格式。其中一个是带字典的列表:

  

[{},{}]

我建议你试试这个:

SELECT t1.varid  as col1,
       t1.var1   as col2,
       t1.var2,
       t1.vardata,
       t2.varid,
       t2.var1,
       t2,
       .var2
  FROM table1 t1, table2 t2
 WHERE     t1.varid = t2.varid
       AND t1.vardata BETWEEN TO_DATE ('20170807', 'YYYYMMDD')
                          AND TO_DATE ('20170808', 'YYYYMMDD')
        --- Give date ranges.                  
       OR   t1.vardata BETWEEN TO_DATE ('20170907', 'YYYYMMDD')
                          AND TO_DATE ('20171008', 'YYYYMMDD')                  
       OR ....
       OR ....

答案 1 :(得分:0)

几乎工作,但似乎是重复和倍增结果创建一个巨大的列表

[
 {
    "Username": "Username", 
    "MFA": "No MFA Enabled", 
    "account": "Account"
 }
]
[
 {
    "Username": "Username", 
    "MFA": "No MFA Enabled", 
    "account": "Account"
 }, 
 {
    "Username": "Username", 
    "MFA": "No MFA Enabled", 
    "account": "Account"
 }
]
[
  {
    "Username": "Username", 
    "MFA": "No MFA Enabled", 
    "account": "Account"
  }, 
  {
    "Username": "Username", 
    "MFA": "No MFA Enabled", 
    "account": "Account"
  }, 
  {
    "Username": "Username", 
    "MFA": "No MFA Enabled", 
    "account": "Account"
  }
]
[
  {
    "Username": "Username", 
    "MFA": "No MFA Enabled", 
    "account": "Account"
  }, 
  {
    "Username": "Username", 
    "MFA": "No MFA Enabled", 
    "account": "Account"
  }, 
  {
    "Username": "Username", 
    "MFA": "No MFA Enabled", 
    "account": "Account"
  }, 
  {
    "Username": "Username", 
    "MFA": "No MFA Enabled", 
    "account": "Account"
  }
]