【发布时间】:2020-10-29 10:54:29
【问题描述】:
我有多层 json 文件,里面有嵌套的 list 和 dictionnary,它们看起来像这样,但大小和级别各不相同:
{
"mass_update": [
{
"lvl-1": "lvl-1.1"
},
{
"lvl-1": "lvl-1.2"
},
{
"lvl-1": "lvl-1.3"
},
[
{
"lvl-2": "lvl-2.1",
"lvl-2": "lvl-2.1.2"
},
[
{
"lvl-3": "lvl-3.1"
},
{
"lvl-3": "lvl-3.2"
},
[
{
"lvl-4": "lvl-4.1",
"lvl-4": "lvl-4.1.2"
},
{
"lvl-4": "lvl-4.2",
"lvl-4": "lvl-4.2.2"
}
]
],
{
"lvl-2": "lvl-2.2",
"lvl-2": "lvl-2.2.2"
},
[
{
"lvl-3": "lvl-3.3"
},
{
"lvl-3": "lvl-3.4"
},
[
{
"lvl-4": "lvl-4.3",
"lvl-4": "lvl-4.3.2"
},
{
"lvl-4": "lvl-4.4",
"lvl-4": "lvl-4.4.2"
}
]
]
]
]
}
我正在尝试读取 json 和 print 每个 key value 组合。当我在嵌套list 的末尾时,我想执行一个function,假设现在执行print("This is the end of the list, yay :-) )"。
我尝试了一些东西,比如创建一个class,它有一个var,我在其中存储了我的dictionnary 或我的list:
class MassUpt:
def __init__(self, my_dict):
self.my_dict = my_dict
def get_my_dict(self):
return self.my_dict
我将obj 中的class 保存在global list 中:
def get_obj(full_dict): #full_dict contains the list "mass_update" that is in all json files
for item in full_dict:
if isinstance(item, list):
obj_dict = MassUpt(item)
mass_upt_dict.append(obj_dict)
return get_obj(item)
else:
obj_dict = MassUpt(item)
mass_upt_dict.append(obj_dict)
print()
然后我执行另一个function,即目前,printingkey value 组合:
def printing_obj_lst(full_dict):
lst_test = []
for item in full_dict:
lst_test.append(item.get_my_dict())
for item in lst_test:
if isinstance(item, list):
print("Calling next object")
else:
for k, v in item.items():
print("Key: " + str(k) + " Value: " + str(v))
这是我执行的main:
full_dict = mass_upt_res_data_json["mass_update"]
get_obj(full_dict)
printing_obj_lst(mass_upt_dict)
这是我的输出:
Key: lvl-1 Value: lvl-1.1
Key: lvl-1 Value: lvl-1.2
Key: lvl-1 Value: lvl-1.3
Calling next object
Key: lvl-2-1 Value: lvl-2.1.1
Key: lvl-2-2 Value: lvl-2.1.2
Calling next object
Key: lvl-3 Value: lvl-3.1
Key: lvl-3 Value: lvl-3.2
Calling next object
Key: lvl-4-1 Value: lvl-4.1
Key: lvl-4-2 Value: lvl-4.1.2
Key: lvl-4-1 Value: lvl-4.2
Key: lvl-4-2 Value: lvl-4.2.2
我没有打印所有key value 组合,我不知道这是否是好的解决方案。重要的是我不要弄平 json,因为列表的末尾可以帮助我知道何时执行 futur function。抱歉发了这么长的帖子,感谢您抽出宝贵的时间阅读!
【问题讨论】:
标签: python json python-3.x list dictionary