python - 从json中提取某些数据

标签 python json api extract

https://www.huobi.com/p/api/contents/

你好,我想从这个 api 中提取所有的标题,看看标题是否有任何变化..我如何用 python 做?

我收到这个错误:

before_set = before['data']['items']['title']
TypeError: list indices must be integers or slices, not str

这是我的代码:

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://www.huobi.com/p/api/contents/').json()
    with open('notice.json', 'w') as current_notice:
        current_notice.write(json.dumps(before))
    print("First run....")

after = requests.get('https://www.huobi.com/p/api/contents/').json()

before_set = before['data']['items']['title']
after_set = after['data']['items']['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            

最佳答案

before['data']['items'] 中包含的数据是一个列表。您将使用以下方式访问第一个项目的标题:

before['data']['items'][0]['title']

要获取所有标题,您可以使用列表理解:

before_set = [item['title'] for item in before['data']['items']]

关于python - 从json中提取某些数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50036071/

相关文章:

python - Django 寻找不同项目的 URL

php - 通过表单向php发送json

php - PHP 的 json_encode 能保证生成 ASCII 字符串吗?

php - Paypal 沙盒 - 错误 10002 : You do not have permission to make this API call

Python NLTK 最大熵分类器错误

python - 检查 Pandas 中的日期时间对象是否有时区?

python - 导入错误: cannot import name 'Enum' from 'discord' (unknown location)

javascript - json最后一个错误返回4

python api - shopify.Variant 404 错误

android - Retrofit 2.0 发布请求