0

我正在使用一个返回 JSON 字符串的 API,其格式如下:

{u'inboxMessages': [{u'fromAddress':
u'BM-2DBYkhiBZCyrBa8J7gFRGrFRSGqtHgPtMvwQ', u'toAddress':
u'BM-2DC7SCTj2gzgrGgMvUCARdrfrsgLyz3iMyN3', u'read': 0, u'msgid':
u'36659a4453e12a085d8fbfeefc58da8fb23f38bfb0984c2983e0ddc31c776038',
u'receivedTime': u'1377986524', u'message':
u'dGVzdGluZyAxIDIgMw0KDQotLQ0KSm9obiBQZXJyeQ0KDQo=\n', u'encodingType':
2, u'subject': u'bWVzc2FnZSAx\n'}, {u'fromAddress':
u'BM-2DBYkhiBZCyrBa8J7gNBrngtgttHgPtMvwQ', u'toAddress':
u'BM-2DC7SCTj2gzgrGgMvUCARdCrfthyz3iMyN3', u'read': 0, u'msgid':
u'2ebe10c788ed47c6c122e3b43ae6642cb15077536c7056ed5088ab2d339c4630',
u'receivedTime': u'1377986557', u'message':
u'VGhpcyBpcyB0aGUgbmV4dCB0ZXN0DQoNCi0tDQpKb2huIFBlcnJ5DQoNCg==\n',
u'encodingType': 2, u'subject': u'dGVzdGluZyAzIDQgNQ==\n'},
{u'fromAddress': u'BM-2DBYkhithgyhyrBa8J7gNBrnSGqtHgPtMvwQ',
u'toAddress': u'BM-2DC7SCTj2gzgrtgtgMvUCARdCogLyz3iMyN3', u'read': 0,
u'msgid':
u'91dffd421c898aab0ffc43a363869a580abec6fa851aa6cf7cefe98263f96c81',
u'receivedTime': u'1377986599', u'message':
u'VGhpcyBpcyB0aGUgM3JkIHRlc3QNCg0hjj0NCkpvaG4gUGVycnkNCg0K\n',
u'encodingType': 2, u'subject': u'dGhpcyBpcyB0aGUgM3Jk\n'}]}

我正在尝试遍历其中的每一个并列出“fromAddress”字段。到目前为止,我可以像这样列出第一个条目:

data = json.loads(api.getAllInboxMessages()) # The API call
print data['inboxMessages'][1]['fromAddress']

上面的代码将从第一条消息中检索 fromAddress。但是我怎样才能找回其他人呢?我知道答案是“只是循环到索引的顶部”但是我怎么知道索引的顶部是什么?

我应该如何处理这个字符串中的所有消息?

谢谢!安东尼

4

1 回答 1

6

很好地格式化字典,你会很容易看到它的结构:

{
    u'inboxMessages': [{
        u'fromAddress': u'BM-2DBYkhiBZCyrBa8J7gFRGrFRSGqtHgPtMvwQ',
        u'toAddress': u'BM-2DC7SCTj2gzgrGgMvUCARdrfrsgLyz3iMyN3',
        u'read': 0,
        u'msgid': u'36659a4453e12a085d8fbfeefc58da8fb23f38bfb0984c2983e0ddc31c776038',
        u'receivedTime': u'1377986524',
        u'message': u'dGVzdGluZyAxIDIgMw0KDQotLQ0KSm9obiBQZXJyeQ0KDQo=\n',
        u'encodingType': 2,
        u'subject': u'bWVzc2FnZSAx\n'
    }, {
        u'fromAddress': u'BM-2DBYkhiBZCyrBa8J7gNBrngtgttHgPtMvwQ',
        u'toAddress': u'BM-2DC7SCTj2gzgrGgMvUCARdCrfthyz3iMyN3',
        u'read': 0,
        u'msgid': u'2ebe10c788ed47c6c122e3b43ae6642cb15077536c7056ed5088ab2d339c4630',
        u'receivedTime': u'1377986557',
        u'message': u'VGhpcyBpcyB0aGUgbmV4dCB0ZXN0DQoNCi0tDQpKb2huIFBlcnJ5DQoNCg==\n',
        u'encodingType': 2,
        u'subject': u'dGVzdGluZyAzIDQgNQ==\n'
    }, {
        u'fromAddress': u'BM-2DBYkhithgyhyrBa8J7gNBrnSGqtHgPtMvwQ',
        u'toAddress': u'BM-2DC7SCTj2gzgrtgtgMvUCARdCogLyz3iMyN3',
        u'read': 0,
        u'msgid': u'91dffd421c898aab0ffc43a363869a580abec6fa851aa6cf7cefe98263f96c81',
        u'receivedTime': u'1377986599',
        u'message': u'VGhpcyBpcyB0aGUgM3JkIHRlc3QNCg0hjj0NCkpvaG4gUGVycnkNCg0K\n',
        u'encodingType': 2,
        u'subject': u'dGhpcyBpcyB0aGUgM3Jk\n'
    }]
}

在这里,您只需遍历列表:

data = json.loads(api.getAllInboxMessages())

for message in data['inboxMessages']:
    print message['fromAddress']
于 2013-09-01T00:39:44.497 回答