如何在Python中读取多层JSON结构里child节点的component_name?
问题描述
现有如下多层JSON结构,已编写部分Python代码读取该JSON文件,需要读取其中desktop节点下child数组内的component_name字段,请求实现方法。
JSON文件内容
{ "layout": { "user": { "pages": { "Home": { "sub_domain_name": "abcd", "title": "Home", "page_id": 1111111, "is_login_required": false, "description": "Description", "sequence": "1", "desktop": [ { "name": "row", "component_id": "31fac419-f1ff-4614", "main_classes": "border-bottom-0 me", "child": [ { "name": "col", "component_id": "087851bc", "component_name": "Card", "size": "12", "main_classes": "-", "classes": "display-6", "height": "-", "width": "-", "items": [] } ] } ] } } } } }
现有Python代码
import json myJsonFile=open("config-2.json")#open json file jsondata=myJsonFile.read()#read json file #parse obj=json.loads(jsondata)#store json data in object list=obj['layout']#read first node print("Length:",len(list)) for i in list: inner_page=list[i]['pages']#read pages node pages_list=inner_page.keys() for j in pages_list: desktop=inner_page[j]['desktop']#read desktop node print(desktop)#print desktop node for k in desktop: print("Component Name:",k['name'])
解决方案
要读取child数组内的component_name字段,只需在遍历desktop数组的循环中,进一步遍历每个row节点下的child数组,提取对应字段即可。修改后的代码如下:
import json # 用with语句打开文件,自动处理文件关闭 with open("config-2.json") as myJsonFile: jsondata = myJsonFile.read() # 解析JSON数据 obj = json.loads(jsondata) layout = obj['layout'] for key in layout: inner_page = layout[key]['pages'] pages_list = inner_page.keys() for page_name in pages_list: desktop = inner_page[page_name]['desktop'] # 遍历desktop中的每个row节点 for row in desktop: # 遍历row下的child数组,提取component_name for child_item in row['child']: print("Component Name:", child_item['component_name'])
补充说明
- 如果
child数组可能为空,可以添加判断避免报错:for row in desktop: # 先判断child数组是否存在且非空 if row.get('child'): for child_item in row['child']: print("Component Name:", child_item['component_name'])
内容的提问来源于stack exchange,提问作者Pooja Patil
相关产品推荐
相关产品推荐

