无法从JSON结果中检索值

时间:2015-08-08 01:28:31

标签: python json rest curl backendless

我通过按属性搜索,将字节转换为字符串,然后从结果中获取objectId值,从具有REST调用的表中检索条目。

new_requests = Popen(['curl',
                  '-H', 'application-id: %s' % backendless_appid,
                  '-H', 'secret-key: %s' % backendless_sk,
                  '-H', 'Content-Type: application/json',
                  '-X', 'GET',
                  '-v', 'https://api.backendless.com/v1/data/Request?where=requestId%3D1'],
                 stdout=PIPE).communicate()[0]

new_requests_str = new_requests.decode(encoding='utf-8')

new_requests_objectid = json.loads(new_requests_str, strict=False)['objectId']

不幸的是,这会产生KeyError: 'objectId'

print(new_requests_str)返回JSON结果,因此问题为new_requests_objectid

{"offset":0,"data":[{"emailAddress":"eric@apakau.com","apiEndpoint":"http://www.yahoo.com","created":1438986033000,"requestId":"1","___class":"Request","ownerId":null,"updated":1439222409000,"objectId":"723B5AEE-5D60-E00E-FF92-ACA3B4629F00","apiSecretkey":"asdfasa","__meta":"{\"relationRemovalIds\":{},\"selectedProperties\":[\"emailAddress\",\"apiEndpoint\",\"created\",\"requestId\",\"___class\",\"ownerId\",\"updated\",\"objectId\",\"apiSecretkey\"],\"relatedObjects\":{}}"}],"nextPage":null,"totalObjects":1}

1 个答案:

答案 0 :(得分:1)

objectId不是new_requests json中的直接键。相反,它是data列表中字典的一部分。所以你需要像那样访问它。很可能请求返回一个包含多个对象(和多个objectId s)的响应,所以我建议将它们保存在列表中,例如 -

new_requests = Popen(['curl',
                  '-H', 'application-id: %s' % backendless_appid,
                  '-H', 'secret-key: %s' % backendless_sk,
                  '-H', 'Content-Type: application/json',
                  '-X', 'GET',
                  '-v', 'https://api.backendless.com/v1/data/Request?where=requestId%3D1'],
                 stdout=PIPE).communicate()[0]

new_requests_str = new_requests.decode(encoding='utf-8')

new_requests_objectIds = []

for data_item in json.loads(new_requests_str, strict=False)['data']:
    new_requests_objectIds.append(data_item['objectId'])