Python中将API返回的JSON数据转换为可用字典或小型数据库的问题
接口数据结构说明
你调用的接口返回的列表每个元素包含5个一级字段,除了buy、sell外,还有adjusted_price、average_price、type_id,你之前遍历漏了这些字段,buy和sell下还嵌套了最高/最低价、成交量、订单数等细分字段。
方法1:转换为可直接查询的字典
将列表转换为以物品ID(type_id)为键的大字典,后续可直接通过物品ID快速查询对应市场数据:
import requests url_final = "你的完整接口地址" response = requests.get(url_final).json() market_data = {} for item in response: current_type_id = item["type_id"] # 按需提取字段,可自行增减 market_data[current_type_id] = { "adjusted_price": item["adjusted_price"], "average_price": item["average_price"], # buy盘字段 "buy_max_price": item["buy"]["max"], "buy_min_price": item["buy"]["min"], "buy_total_volume": item["buy"]["volume"], "buy_order_count": item["buy"]["orderCount"], # sell盘字段 "sell_min_price": item["sell"]["min"], "sell_max_price": item["sell"]["max"], "sell_total_volume": item["sell"]["volume"], "sell_order_count": item["sell"]["orderCount"] } # 测试查询示例:查询type_id为34的三钛合金市场数据 print(market_data.get(34))
如果需要查看buy/sell下所有可用字段,可在遍历中加一行print(item["buy"].keys())打印所有键名。
方法2:存储到本地小型SQLite数据库
使用Python内置的sqlite3模块无需额外安装依赖,可直接将数据落地到本地数据库持久化存储:
import requests import sqlite3 # 请求数据 url_final = "你的完整接口地址" response = requests.get(url_final).json() # 连接本地数据库,文件不存在会自动创建 conn = sqlite3.connect("eve_market.db") cursor = conn.cursor() # 创建市场数据表 cursor.execute(''' CREATE TABLE IF NOT EXISTS market_stat ( type_id INTEGER PRIMARY KEY, adjusted_price REAL, average_price REAL, buy_max REAL, buy_min REAL, buy_volume INTEGER, buy_order_count INTEGER, sell_max REAL, sell_min REAL, sell_volume INTEGER, sell_order_count INTEGER ) ''') # 批量写入数据 for item in response: cursor.execute(''' INSERT OR REPLACE INTO market_stat (type_id, adjusted_price, average_price, buy_max, buy_min, buy_volume, buy_order_count, sell_max, sell_min, sell_volume, sell_order_count) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ''', ( item["type_id"], item["adjusted_price"], item["average_price"], item["buy"]["max"], item["buy"]["min"], item["buy"]["volume"], item["buy"]["orderCount"], item["sell"]["max"], item["sell"]["min"], item["sell"]["volume"], item["sell"]["orderCount"] )) # 提交更改并关闭连接 conn.commit() conn.close()
内容的提问来源于stack exchange,提问作者YepNope
相关产品推荐
相关产品推荐

