簡體   English   中英

從json提取某些數據

[英]Extracting certain data from json

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']是一個列表。 您將使用以下命令訪問第一項的標題:

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

要獲取所有標題,可以使用列表理解:

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

您具有ID列表以實現最佳可視化效果,我建議您將數據與ID進行比較,例如:

bitems = before.get('data', {}).get('items', [])
before_data = [(item.get('id'), item.get('title')) for item in bitems]
aitems = after.get('data', {}).get('items', [])
after_data = [(item.get('id'), item.get('title')) for item in aitems]

compare = set(before_data) ^ set(after_data)
print(compare)

這里的問題是response ['data'] ['items']以列表的形式出現

type(response['data']['items'])
<class 'list'>

您可以使用列表理解來解決此問題,也可以嘗試使用集合中的默認字典

這是因為before['data']['items']具有多個項目,因此它返回一個數組

您可以像這樣遍歷列表:

for item in before['data']['items']:
  print item['title']

或者您也可以將所有標題保存到一個變量中,例如:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM