在 Python 中解析 HTTP 响应 [英] Parsing HTTP Response in Python

查看:43
本文介绍了在 Python 中解析 HTTP 响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想操作 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.

有没有办法将字符串转换为 dict 以便我可以迭代它?还是我只需要按原样解析它(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') 将字符串转换为 dict,所以我只需要将字节类型转换为字符串类型.我通过解码对 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆