简体   繁体   English

如何获取urllib2以数组形式返回数据

[英]how to get urllib2 to return data as an array

Not sure if this is even possible, but if so it would be awesome. 不知道这是否可能,但是如果可以,那就太好了。

My code is: 我的代码是:

url = "https://*myDomain*.zendesk.com/api/v2/organizations/*{id}*/tags.json"
req = urllib2.request(url)
password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
password_manager.add_password(None, url, 'example@domain.com', 'password')
auth_manager = urllib2.HTTPBasicAuthHandler(password_manager)
opener = urllib2.build_opener(auth_manager)
urllib2.install_opener(opener)
response = urllib2.urlopen(req)
tagsA = response.read()
print tagsA

Now the data that is returned is: 现在返回的数据是:

{"tags":[]}

The API call itself returns the following API调用本身返回以下内容

{
tags: []
}

However trying to access the list doesn't work as it seems to treat tagsA as a string. 但是,尝试访问列表不起作用,因为似乎将tagA视为字符串。 I would like it to treat it as a list so that I could check if 'tags' is empty. 我希望将其视为一个列表,以便可以检查“标签”是否为空。

Any help would be greatly appreciated!!! 任何帮助将不胜感激!!!

You need to load json string into python dictionary via json.loads() : 您需要通过json.loads()将json字符串加载到python字典中:

import json

...

tagsA = json.loads(response.read())
print tagsA['tags']

Or, pass response to json.load() (thanks to @JF Sebastian's comment): 或者,将response传递给json.load() (由于@JF Sebastian的评论):

tagsA = json.load(response)
print tagsA['tags']

You need to json.load (or json.loads ) the response body. 您需要json.load (或json.loads )响应主体。

However, if you're going to do any kind of semi-complicated HTTP calls (authentication, cookies, etc.) in Python, you should really be using Kenneth Reitz's excellent Requests library ( http://python-requests.org/ ) instead of urllib calls. 但是,如果您打算在Python中进行任何半复杂的HTTP调用(身份验证,Cookie等),则应该使用Kenneth Reitz出色的Requests库( http://python-requests.org/ )而不是urllib调用。 Your entire code would become: 您的整个代码将变为:

import requests
response = requests.get(url, auth=("my_username", "my_password"))
tagsA = response.json()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM