无法在对象内循环通过JSON数组

时间:2016-10-06 02:13:49

标签: python json

这是我的JSON返回对象的样子:

{
    u'Policy': u'{
        "Version": "2012-10-17",
        "Statement": [{
            "Sid": "xxxxx",
            "Effect": "Allow",
            "Principal": {
                "Service": "cloudtrail.amazonaws.com"
            },
            "Action": "s3:GetBucketAcl",
            "Resource": "arn:aws:s3:::xxxxx"
        },
        {
            "Sid": "yyyyyyy",
            "Effect": "Allow",
            "Principal": {
                "Service": "cloudtrail.amazonaws.com"
            },
            "Action": "s3:PutObject",
            "Resource": "arn:aws:s3:::xxxxx/AWSLogs/00000000/*",
            "Condition": {
                "StringEquals": {
                    "s3:x-amz-acl": "bucket-owner-full-control"
                }
            }
        }]
    }',
    'ResponseMetadata': {
        'HTTPHeaders': {
            'content-length': '479',
            'content-type': 'application/json',
            'date': 'Thu,
            06Oct201602: 07: 48GMT',
            'server': 'AmazonS3',
            'x-amz-id-2': 'xxxxxxx',
            'x-amz-request-id': 'xxxxxxx'
        },
        'HTTPStatusCode': 200,
        'HostId': 'xxxxxxx',
        'RequestId': 'xxxxxxx',
        'RetryAttempts': 0
    }
}

这就是我试图通过语句循环的方式:

for stmt in bucket_policy['Policy']['Statement']:
   print stmt

这是我得到的错误:

TypeError: string indices must be integers

是因为返回数据是Unicode还是我循环的方式有问题?

2 个答案:

答案 0 :(得分:0)

您应该使用

将JSON转换为字典
import json
mydict = json.load(bucket_policy)

然后循环:

for stmt in mydict['Policy']['Statement']:
   print stmt

答案 1 :(得分:0)

在问题中显示的方式,bucket_policy['Policy']包含字符串,而不是字典。

将其定义为字典(即在开头删除u',在结尾处删除')或使用json.loads解析JSON。