【发布时间】:2022-01-04 14:46:45
【问题描述】:
我提出了一个 API 请求:
# set up the request parameters
params = {
'api_key': 'XXXXXXXXXXXXXXXXXXXXXXXXX',
'type': 'product',
'item_id': 'XXXXXXXXX',
'url': 'https://www.somestore.com',
'output': 'json'
}
# make the http GET request to the API
api_result = requests.get('https://api.shopperapi.com/request', params)
product_data = json.loads(api_result.text)
if ((product_data["product.buybox_winner.seller.name"]=="MyStore.com") and (product_data["product.buybox_winner.availability.in_stock"]=="False")):
my_Mailer("Its out of stock")
JSON 格式为:
{
"request_info": {},
"request_metadata": {},
"request_parameters": {},
"product": {
"brand": "XXX",
"title": "MyProductName",
"upc": "XXXXXXXX",
"item_id": "XXXXXXXXXX",
"product_id": "XXXXXXXXXX",
"item_number": "XXXXXXXXX",
"model": "85888",
"ratings_total": 45,
"rating": 4.6,
"type": "Housewares",
"buybox_winner": {
"price": 100.0,
"was_price": 199.95,
"currency_symbol": "$",
"id": "XXXXXXXXXXXXXXXXXXXXXXXX",
"": {
"name": "MyStore.com",
"id_secondary": "XXXXXXXXXXXXXXXXXXXXXXXXXX",
"id": "XXXXXXXXXXXXXXXXXXXXXXXXXX"
},
"availability": {
"raw": "OUT_OF_STOCK",
"in_stock": false,
"preorder": false
}
}
我的错误是 KeyError: 'product.buybox_winner.seller.name'
我似乎无法解析这个 JSON 文件,因为我不知道如何正确引用密钥来检查它。
【问题讨论】:
-
"product.buybox_winner.seller.name"字典中不存在此键。看来您正在尝试访问 json 中的路径。字典不支持。你需要做product_data['product']['buybox_winner']['seller']['name']
标签: python json api parsing key