从 API 接收 .json 数据并提取信息以供以后使用

问题描述 投票:0回答:1

我刚刚开始对 Raspberry PI 进行编程。 我在提取从 API 获取的信息时遇到问题。

  1. 我将图片发送到“Goolge Visions API”以提取“setname”和“cardid”
  2. 然后我向“Scryfall API”发送 API 请求以接收 .json 数据。
  3. 从这些数据中我需要提取“color_identity”“colors”和“eur”。

不幸的是,我对Python了解不够,无法解决这个问题。 这是我在网上浏览了几个小时后想到的。

import requests
import json

setname = "xln"      #this is the ID of the Set*
cardid = "96"        #this is the set specific id of the card*

response_API = requests.get('https://api.scryfall.com/cards/'setname'/'cardid'.json')
data = response_API.text
parse_json = json.loads(data)
card_list = []

for item in json_array:
    card_details = {"color_identity":None, "colors":None, "eur":None}
    card_details['color_identity'] = item ['color_identity']
    card_details['colors'] = item ['colors']
    card_details['eur'] = item ['eur']
    card_list.append(card_details)

print(card_list)

python api raspberry-pi request
1个回答
0
投票

您的网址无效,因此代码经过测试!

你可以这样做,但是还有很多其他选项可以在 python 中处理请求和 json 数据。

import json

setname = "xln"      #this is the ID of the Set*
cardid = "96"        #this is the set specific id of the card*

response_API = requests.get(f'https://api.scryfall.com/cards/{setname}/{cardid}.json')
if response_API.status_code == 200:
    data = response_API.json()
    assert isinstance(data, list), "response is not a list"
    card_list = [
        {
            'color_identity': x.get('color_identity'),
            'colors': x.get('colors'),
            'eur': x.get('eur')
        } for x in data
    ]
else:
    print('No correct request was made')
    print(response_API.content.decode())
  1. 对API的请求就像你一样(但我更喜欢
    f
    -字符串,但你的方法也可能有效。
  2. 检查响应代码是否为 200:https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
  3. 读取字典中的数据(Python对象)
  4. 检查数据是否为列表类型(这是必需的,因为您要查看列表以提取所有卡详细信息)。
  5. 使用列表理解来检查数据列表中的每个项目(现在是列表类型,因为之前已检查过)。使用 get 方法,因为如果键不在元素字典中,它会返回
    None
    https://docs.python.org/3/tutorial/datastructures.html#list-compressiveshttps://www.w3schools.com/python/ref_dictionary_get.asp
© www.soinside.com 2019 - 2024. All rights reserved.