Python解析嵌套JSON:API返回结果中筛选playerID及输出指定块问题
解决API JSON筛选:找不到嵌套playerID及输出完整type相关JSON块的问题
先看你提供的JSON片段,首先明确一点:当前展示的participant对象里并没有直接命名为playerID的字段——不过这里的顶级id字段(也就是included[0].id)大概率就是你要找的玩家唯一标识,很多游戏类API会用这个资源ID来对应玩家账号。
接下来针对你两个核心需求,给出具体的实现方案:
1. 筛选并输出包含type字段的完整JSON块
不管你用什么语言,核心逻辑都是遍历included数组,找到type匹配目标值(比如这里的participant)的项,然后输出整个对象。
JavaScript示例
// 假设API返回的完整数据存在response变量中 const apiResponse = { /* 你的完整JSON数据 */ }; // 筛选type为"participant"的所有项 const targetItems = apiResponse.included?.filter(item => item.type === "participant") || []; // 逐个输出完整JSON块(保留所有嵌套字段) targetItems.forEach(item => { console.log("匹配到的完整JSON块:"); console.log(JSON.stringify(item, null, 2)); });
Python示例
import json # 假设API返回的JSON字符串已解析为字典 api_response = json.loads("""{ "included": [ { "type": "participant", "id": "efb753a7-bc6b-4cf0-925a-df4693b51690", "attributes": { "actor": "", "shardId": "pc-na", "stats": { "DBNOs": 0, "assists": 0, "boosts": 0, "damageDealt": 21.78, "deathType": "byplayer", "headshotKills": 0, "heals": 1, "killPlace": 69, "killPoints": 1204 } } } ] }""") # 筛选type为participant的项 target_items = [item for item in api_response.get("included", []) if item.get("type") == "participant"] # 输出完整JSON块 for item in target_items: print("匹配到的完整JSON块:") print(json.dumps(item, indent=2))
2. 查找嵌套的playerID字段
如果API文档明确说明存在playerID字段,那可能是你提供的JSON片段不完整。比如有些API会把玩家ID放在attributes的子字段里,或者在relationships(JSON:API规范常见结构)中。如果不确定位置,可以用深度遍历的方法查找:
JavaScript深度查找示例
function deepFindField(obj, fieldName) { for (const key in obj) { if (key === fieldName) return obj[key]; if (typeof obj[key] === "object" && obj[key] !== null) { const result = deepFindField(obj[key], fieldName); if (result !== undefined) return result; } } return "未找到该字段"; } // 在筛选后的项中查找playerID targetItems.forEach(item => { const playerID = deepFindField(item, "playerID"); console.log("找到的playerID:", playerID); });
Python深度查找示例
def deep_find_field(obj, field_name): if isinstance(obj, dict): for key, value in obj.items(): if key == field_name: return value result = deep_find_field(value, field_name) if result is not None: return result elif isinstance(obj, list): for item in obj: result = deep_find_field(item, field_name) if result is not None: return result return "未找到该字段" # 在筛选后的项中查找playerID for item in target_items: player_id = deep_find_field(item, "playerID") print(f"找到的playerID:{player_id}")
另外补充:如果API里并没有playerID这个字段,那前面提到的顶级id字段(efb753a7-bc6b-4cf0-925a-df4693b51690)就是玩家的唯一标识,可以直接用它来替代playerID的作用。
内容的提问来源于stack exchange,提问作者user3901330




