用Python解析HTTP响应 [英] Parsing HTTP Response in Python
问题描述
我想在 THIS 网址中处理信息.我可以成功打开它并阅读其内容.但是我真正想做的是扔掉所有我不想要的东西,并操纵我想要保留的东西.
I want to manipulate the information at THIS url. I can successfully open it and read its contents. But what I really want to do is throw out all the stuff I don't want, and to manipulate the stuff I want to keep.
有没有一种方法可以将字符串转换为字典,以便我可以对其进行迭代?还是我只需要按原样解析它(str类型)?
Is there a way to convert the string into a dict so I can iterate over it? Or do I just have to parse it as is (str type)?
from urllib.request import urlopen
url = 'http://www.quandl.com/api/v1/datasets/FRED/GDP.json'
response = urlopen(url)
print(response.read()) # returns string with info
推荐答案
当我打印response.read()
时,我注意到b
被放在字符串的前面(例如b'{"a":1,..
). "b"代表字节,并用作要处理的对象类型的声明.因为我知道可以使用json.loads('string')
将字符串转换为字典,所以我只需要将字节类型转换为字符串类型即可.我通过解码对utf-8 decode('utf-8')
的响应来完成此操作.一旦它是字符串类型,我的问题就解决了,我可以轻松地遍历dict
.
When I printed response.read()
I noticed that b
was preprended to the string (e.g. b'{"a":1,..
). The "b" stands for bytes and serves as a declaration for the type of the object you're handling. Since, I knew that a string could be converted to a dict by using json.loads('string')
, I just had to convert the byte type to a string type. I did this by decoding the response to utf-8 decode('utf-8')
. Once it was in a string type my problem was solved and I was easily able to iterate over the dict
.
我不知道这是最快还是最"pythonic"的编写方式,但是它可以工作,并且总是需要一些时间进行优化和改进!我的解决方案的完整代码:
I don't know if this is the fastest or most 'pythonic' way of writing this but it works and theres always time later of optimization and improvement! Full code for my solution:
from urllib.request import urlopen
import json
# Get the dataset
url = 'http://www.quandl.com/api/v1/datasets/FRED/GDP.json'
response = urlopen(url)
# Convert bytes to string type and string type to dict
string = response.read().decode('utf-8')
json_obj = json.loads(string)
print(json_obj['source_name']) # prints the string with 'source_name' key
这篇关于用Python解析HTTP响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!