繁体   English   中英

从JSON提取“标题”数据

[英]Extracting “title” data from JSON

我有这个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       

访问密钥之前,应先检查该密钥在词典中是否可用。

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")
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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM