Python 提取;标题「;来自JSON的数据
我有这个API 我想从中提取标题并进行比较,看看api是否有任何更改或更新。。。我犯了一个错误Python 提取;标题「;来自JSON的数据,python,json,api,difference,Python,Json,Api,Difference,我有这个API 我想从中提取标题并进行比较,看看api是否有任何更改或更新。。。我犯了一个错误 before_set = before['data']['title'] KeyError: 'title' 我的代码如下: import requests import json try: with open('notice.json', 'r') as current_notice: before = json.loads(current_notice.read())
before_set = before['data']['title']
KeyError: 'title'
我的代码如下:
import requests
import json
try:
with open('notice.json', 'r') as current_notice:
before = json.loads(current_notice.read())
except IOError:
before = requests.get('https://manager.upbit.com/api/v1/').json()
with open('notice.json', 'w') as current_notice:
current_notice.write(json.dumps(before))
print("First run....")
after = requests.get('https://manager.upbit.com/api/v1/').json()
before_set = before['data']['title']
after_set = after['data']['title']
new_set = after_set - before_set
while True:
try:
if not new_set:
print("No change... Exiting.")
if new_set:
print("There are changes")
except Exception as e:
print(e)
pass
在访问字典之前,应该首先检查字典中是否有密钥
if 'title' in before['data']:
before_set = before['data'].get('title')
比这更好的是,尝试使用.get()方法,如果请求的键不存在,它将返回None
before_set = before['data'].get('title')
如果在before['data']中不存在大小写'title',您还可以返回一些“默认值”
before_set = before['data'].get('title', "No Title")
它不应该在['data']['list'][index]['title']之前,其中index=0,1,2。。。你想比较api中的所有标题吗?请不要破坏你的帖子。通过在Stack Exchange网络上发布,您已授予SE分发该内容的不可撤销的权利(根据)。根据SE政策,任何故意破坏行为都将被恢复。虽然此代码可能会回答此问题,但提供有关此代码为什么和/或如何回答此问题的其他上下文将提高其长期价值。
import requests, json
url = "https://api-manager.upbit.com/api/v1/notices?page=1"
response = json.loads(requests.get(url).content)
title_data = [item.get("title", None).encode("utf-8") for item in response["data"]["list"]]
print(title_data)