如何检测API返回JSON的position/number字段并转为int类型
处理API返回JSON中字段随机变化的问题
这问题其实挺常见的,API字段不稳定确实头疼,不过咱们可以通过检查字段存在性的方式来处理,核心逻辑就是依次检查可能的目标字段名,找到后将其值转换为int类型即可。下面给你举几个常用语言的实现例子:
Python 实现
假设你已经用json.loads()把API返回的JSON字符串解析成了Python字典:
import json # 示例API返回的JSON字符串 api_json_str = '''{"now": [{"time": {"starts_in": 0, "ends_in": 79580, "starts_at": 0, "ends_at": "2018-01-21T08:00:00.788Z"}, "coins": {"free": 8, "first_win": 16, "max": 52, "collected": 0}, "unk1": -88317689, "position": 1, "xp_multiplier": 0, "location_scid": {"scid_type": 15, "scid_id": 1}, "tid": "TID_WANTED_3", "location": "Terre", "mode": {"name": "Bty", "color": "#0884FA", "description": " The team wins!"}, "unk4": 0, "info": "", "unk5": 0, "unk6": 0}, {"time": {"starts_in": 0, "ends_in": 36380, "starts_at": 0, "ends_at": "2018-01-20T20:00:00.788Z"}, "coins": {"free": 24, "first_win": 0, "max": 32, "collected": 0}}], "later": [{"time": {"starts_in": 79580, "ends_in": 165980, "starts_at": "2018-01-21T08:00:00.788Z", "ends_at": "2018-01-22T08:00:00.788Z"}, "coins": {"free": 8, "first_win": 16, "max": 52, "collected": 0}, "unk1": -88217689, "position": 1, "xp_multiplier": 0, "location_scid": {"scid_type": 15, "scid_id": 7}, "tid": "TID_GOLDRUSH_1", "location": "Mine", "mode": {"name": "Grab", "color": "#AA57CF", "description": " An. "}}]}''' data = json.loads(api_json_str) # 遍历now数组中的每个对象 for item in data["now"]: # 定义可能的目标字段列表,按优先级排序 possible_fields = ["position", "number"] target_value = None # 循环检查字段是否存在 for field in possible_fields: if field in item: # 转换为int类型,即使值是字符串也能处理 target_value = int(item[field]) break if target_value is not None: print(f"获取到的排序值:{target_value},类型:{type(target_value)}") else: # 根据业务需求处理未找到字段的情况,比如设默认值或抛出异常 print("未找到position或number字段,使用默认值0") target_value = 0
JavaScript 实现
如果是前端场景,解析后的JSON是JavaScript对象:
// 示例API返回的JSON对象 const data = {"now": [{"time": {"starts_in": 0, "ends_in": 79580, "starts_at": 0, "ends_at": "2018-01-21T08:00:00.788Z"}, "coins": {"free": 8, "first_win": 16, "max": 52, "collected": 0}, "unk1": -88317689, "position": 1, "xp_multiplier": 0, "location_scid": {"scid_type": 15, "scid_id": 1}, "tid": "TID_WANTED_3", "location": "Terre", "mode": {"name": "Bty", "color": "#0884FA", "description": " The team wins!"}, "unk4": 0, "info": "", "unk5": 0, "unk6": 0}, {"time": {"starts_in": 0, "ends_in": 36380, "starts_at": 0, "ends_at": "2018-01-20T20:00:00.788Z"}, "coins": {"free": 24, "first_win": 0, "max": 32, "collected": 0}}], "later": [{"time": {"starts_in": 79580, "ends_in": 165980, "starts_at": "2018-01-21T08:00:00.788Z", "ends_at": "2018-01-22T08:00:00.788Z"}, "coins": {"free": 8, "first_win": 16, "max": 52, "collected": 0}, "unk1": -88217689, "position": 1, "xp_multiplier": 0, "location_scid": {"scid_type": 15, "scid_id": 7}, "tid": "TID_GOLDRUSH_1", "location": "Mine", "mode": {"name": "Grab", "color": "#AA57CF", "description": " An. "}}]}; // 遍历now数组 data.now.forEach(item => { const possibleFields = ["position", "number"]; let targetValue = null; for (const field of possibleFields) { if (item.hasOwnProperty(field)) { // 使用parseInt确保转换为整数,第二个参数10是指定十进制 targetValue = parseInt(item[field], 10); break; } } if (targetValue !== null) { console.log(`获取到的排序值:${targetValue},类型:${typeof targetValue}`); } else { // 未找到字段时的 fallback 逻辑 console.log("未找到position或number字段,使用默认值0"); targetValue = 0; } });
额外注意事项
- 类型安全:即使API返回的字段值是字符串(比如
"position": "1"),int()(Python)或parseInt()(JavaScript)也能正常转换为整数类型。 - 扩展性:如果后续API可能新增其他类似字段(比如
rank),只需把新字段名添加到possible_fields列表中即可,无需修改核心逻辑。 - 异常处理:如果API可能返回非数字类型的值(比如
"position": "abc"),建议加上异常捕获逻辑,避免程序崩溃。
内容的提问来源于stack exchange,提问作者user9243753
相关产品推荐
相关产品推荐

