Python json解码和解析数据

时间:2014-05-11 23:25:40

标签: python json

我已经设法从API获取json数据并拉出我需要的部分。我只想将公共URL部分解析为输出。这是我的代码:

import json
import httplib as client
headers = {"Content-type": "application/json"}
params = json.dumps({"auth": {"passwordCredentials": {"username": "myusername",         "password": "mypassword"}}})
conn = client.HTTPSConnection("lon.identity.api.rackspacecloud.com:443")
conn.request("POST", "/v2.0/tokens", params, headers)
response = conn.getresponse()
output = response.read()
data = json.loads(output)
token = data['access']['serviceCatalog']
print(token)

这是输出数据:

[{"endpoints": [{"region": "LON","publicURL": "https://storage101.lon3.clouddrive.com/v1/MossoCloudFS_bfe4a309-40cf-49b8-acd0-d15f4865542f3","internalURL": "https://snet-storage101.lon3.clouddrive.com/v1/MossoCloudFS_bfe4a309-40cf-49b8-acd0-d15f48vdwds3","tenantId": "MossoCloudFS_bfe4a309-40cf-49b8-acd0-d15f486e82f3"}],"type": "object-store","name": "cloudFiles"}]

现在在我的代码中我尝试过:

token = data['access']['serviceCatalog']['endpoints']['publicURL']

但是我得到:TypeError:list indices必须是整数,而不是str

如何解析publicURL?

非常感谢

3 个答案:

答案 0 :(得分:0)

data是一个列表(有一个元素恰好是字典),但是你试图像字典一样使用它。

>>> type(data)
<class 'list'>

尝试

data = data[0]

>>> type(data)
<class 'dict'>

答案 1 :(得分:0)

data['access']['serviceCatalog']不直接包含dict,而是包含唯一元素为dict的列表。类似地,endpoints dict的值是一个列表,其唯一成员是dict。试试这个:

token = data['access']['serviceCatalog'][0]['endpoints'][0]['publicURL']

通过以下评论回答问题,如果有多个端点,您可以使用list comprehension获取所有公开网址。

urls = [x['endpoints'][0]['publicURL'] for x in data['access']['serviceCatalog']]

答案 2 :(得分:0)

输出数据是一个数组,您需要使用索引访问该数据。

在这种情况下是:

token = data[0][xxx][xxx]

虽然使用输出数据,访问“publicURL”数据的正确语法是:

data[0]["endpoints"][0]["publicURL"]

示例:

>>> data = [{"endpoints": [{"region": "LON","publicURL": "https://storage101.lon3.clouddrive.com/v1/MossoCloudFS_bfe4a309-40cf-49b8-acd0-d15f4865542f3","internalURL": "https://snet-storage101.lon3.clouddrive.com/v1/MossoCloudFS_bfe4a309-40cf-49b8-acd0-d15f48vdwds3","tenantId": "MossoCloudFS_bfe4a309-40cf-49b8-acd0-d15f486e82f3"}],"type": "object-store","name": "cloudFiles"}]
>>> data[0]["endpoints"][0]["publicURL"]
'https://storage101.lon3.clouddrive.com/v1/MossoCloudFS_bfe4a309-40cf-49b8-acd0-d15f4865542f3'