如何用Python提取嵌套父子结构JSON中的特定数据
从嵌套JSON结构中提取信息并验证用户输入
针对你遇到的嵌套JSON结构提取问题,核心是要逐层遍历嵌套的数组和对象,把所有目标用户信息收集后再做匹配。以下是修改后的代码和关键点说明:
修改后的完整代码
import json # 加载嵌套JSON数据 with open('jsondatabase.json', 'r') as f: data = json.load(f) # 收集所有嵌套的用户信息到列表 users = [] # 遍历Parent数组中的每个父级对象 for parent_item in data['Parent']: # 遍历父级对象下的所有子分组(Parent_1、Parent_2等) for group_key in parent_item: group_data = parent_item[group_key] # 遍历子分组中的每个用户对象 for user in group_data: # 统一键名格式,方便后续匹配 users.append({ 'id': user['ID'], 'name': user['Name'] }) # 用户输入交互 print("Please enter your numerical identifier and name: ") user_id = input("Numerical identifier: ") user_name = input("Name: ") # 检查输入是否匹配任何用户信息 match_found = False for user in users: if user['id'] == user_id and user['name'] == user_name: match_found = True break # 输出结果 print("Your inputs matched. Congrats." if match_found else "Your inputs did not match our data. Please try again.")
关键说明
多层遍历逻辑
- 你的目标JSON中,
Parent是一个数组,每个元素是包含多个子分组(Parent_1、Parent_2)的对象 - 每个子分组又是数组,里面才是包含
Name和ID的用户对象,因此需要三层循环来逐层提取所有用户信息
- 你的目标JSON中,
键名统一处理
- 注意原JSON中用户信息的键是
Name和ID(首字母大写),和你最初代码中的name、identifier对应,收集时统一格式避免大小写匹配错误
- 注意原JSON中用户信息的键是
灵活匹配场景
如果只需要匹配特定子分组(比如仅Parent_1),可以简化遍历逻辑:users = [] # 直接定位到Parent_1数组 for user in data['Parent'][0]['Parent_1']: users.append({ 'id': user['ID'], 'name': user['Name'] })
内容的提问来源于stack exchange,提问作者Shalofty
相关产品推荐
相关产品推荐

