Unable to loop thru JSON array inside an object
<p>This is how my JSON return object looks like:</p>

<pre><code>{
    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
    }
}
</code></pre>

<p>This is how I am trying to loop thru Statements:</p>

<pre><code>for stmt in bucket_policy['Policy']['Statement']:
   print stmt
</code></pre>

<p>This is the error I am getting:</p>

<pre><code>TypeError: string indices must be integers
</code></pre>

<p>Is it because the return data is Unicode or something wrong with the way I am looping?</p>

<p>The way it's shown in your question, <code>bucket_policy['Policy']</code> contains a string, not a dictionary.</p>

<p>Either define it as a dictionary (i.e. get rid of <code>u'</code> at the beginning and <code>'</code> at the end) or parse the JSON with <a href="https://docs.python.org/3/library/json.html#json.loads" rel="nofollow"><code>json.loads</code></a>.</p>

python json