JSON File:
{
"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 code:**
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'])
i want to read component_name from child
CodePudding user response:
should be possible using:
print(ob["layout"]["user"]["pages"]["Home"]["desktop"][0]["child"][0]["component_name"])
Which should return: "Card"
CodePudding user response:
You have to select the item that is [0]
and check the name from the dict
.
Here is the working code:
import json
myJsonFile=open("config-2.json")
jsondata=myJsonFile.read()
obj=json.loads(jsondata)
list=obj['layout']
for i in list:
inner_page=list[i]['pages']
pages_list=inner_page.keys()
for j in pages_list:
desktop=inner_page[j]['desktop']
child_keys=desktop[0]['child']
for k in child_keys:
print (k['component_name'])
Output:
Card