【发布时间】:2021-03-21 07:46:41
【问题描述】:
我从 API 和 Python 开始。下面的代码可以正常工作。
import requests
import json
def jprint(obj):
# create a formatted string of the Python JSON object
text = json.dumps(obj, sort_keys=True, indent=4)
print(text)
response = requests.get("http://api.open-notify.org/astros.json")
print(response.status_code)
print(response.json())
print()
jprint(response.json())
但是当我尝试做一些更可重用的事情以供以后使用时,我错过了一些东西......如何解决错误?
raise TypeError(f'Object of type {o.class.name} ' TypeError:DataFeed 类型的对象不是 JSON 可序列化的
感谢您的帮助。
import requests
import json
"""Open APIs From Space: https://www.dataquest.io/blog/python-api-tutorial/
"""
class DataFeed:
base_url = "http://api.open-notify.org/"
number_of_people_in_space = "astros.json"
def __init__(self):
pass
def _build_url(self):
url = f"{self.base_url}" \
f"{self.number_of_people_in_space}"
return url
def get(self, url):
response = requests.get(url)
content = response.json()
print(url)
print(response.status_code)
print(response.json())
def get_data_feed(self):
url = self._build_url()
self.get(url)
def jprint(obj):
# create a formatted string of the Python JSON object
text = json.dumps(obj, sort_keys=True, indent=4)
print(text)
message = DataFeed()
message.get_data_feed()
message.jprint()
【问题讨论】:
标签: python json python-3.x api