Col*_*len 29 api json dictionary urlopen python-3.x
我想操纵这个网址上的信息.我可以成功打开它并阅读其内容.但我真正想要做的就是抛弃我不想要的所有东西,并操纵我想要保留的东西.
有没有办法将字符串转换为字典,以便我可以迭代它?或者我只需按原样解析它(str类型)?
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
Run Code Online (Sandbox Code Playgroud)
Col*_*len 62
这已经解决了.
当我打印时,response.read()我注意到它b已经预先填充到字符串中(例如b'{"a":1,..)."b"代表字节,用作您正在处理的对象类型的声明.因为,我知道字符串可以通过使用转换为dict json.loads('string'),我只需要将字节类型转换为字符串类型.我通过解码对utf-8的响应来做到这一点decode('utf-8').一旦它是一个字符串类型我的问题解决了,我很容易迭代dict.
我不知道这是否是最快或最"pythonic"的写作方式,但它有效,而且总是在优化和改进之后的时间!我的解决方案的完整代码:
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
Run Code Online (Sandbox Code Playgroud)
如果有人碰巧通过谷歌找到这个,我希望这会有所帮助.我能给出的最好的建议是,仔细阅读你的错误,并密切关注你收到的输出.
Sha*_*tal 10
您也可以使用python的请求库.
import requests
url = 'http://www.quandl.com/api/v1/datasets/FRED/GDP.json'
response = requests.get(url)
dict = response.json()
Run Code Online (Sandbox Code Playgroud)
现在你可以像python字典一样操纵"dict"了.
json在Python 3中使用Unicode文本(JSON格式本身仅根据Unicode文本定义),因此您需要解码HTTP响应中接收的字节.r.headers.get_content_charset('utf-8')得到你的字符编码:
#!/usr/bin/env python3
import io
import json
from urllib.request import urlopen
with urlopen('https://httpbin.org/get') as r, \
io.TextIOWrapper(r, encoding=r.headers.get_content_charset('utf-8')) as file:
result = json.load(file)
print(result['headers']['User-Agent'])
Run Code Online (Sandbox Code Playgroud)
io.TextIOWrapper这里没有必要使用:
#!/usr/bin/env python3
import json
from urllib.request import urlopen
with urlopen('https://httpbin.org/get') as r:
result = json.loads(r.read().decode(r.headers.get_content_charset('utf-8')))
print(result['headers']['User-Agent'])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
90065 次 |
| 最近记录: |