提取"标题"来自JSON的数据

时间:2018-04-27 05:32:58

标签: python json api difference

我有这个API ..

https://manager.upbit.com/api/v1/

我想从中提取标题并进行比较以查看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())
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       

2 个答案:

答案 0 :(得分:0)

在访问密钥之前,您应首先检查密钥是否在字典中可用。

if 'title' in before['data']:
    before_set = before['data'].get('title')

更好的是,尝试使用.get()方法,如果请求的密钥不存在,它将返回None。

before_set = before['data'].get('title')

您还可以返回一些"默认值",如果案例'标题'在['数据']

之前不存在
before_set = before['data'].get('title', "No Title")

答案 1 :(得分:0)

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)