【发布时间】:2021-10-22 18:38:32
【问题描述】:
所以我在这里有一个大的 JSON 文件,看起来像这样:
data = {
"Module1": {
"Description": "",
"Layer": "1",
"SourceDir": "pathModule1",
"Attributes": {
"some",
},
"Vendor": "comp",
"components":{
"Component1": {
"path": "something",
"includes": [
"include1",
"include2",
"include3",
"include4",
"include5"
]
"generated:" "txt"
"memory:" "txt"
etc
},
"Component2":{
"path": "something",
"includes": [
"include1",
"include2",
"include3",
"include4",
"include5"
]
"generated:" "txt"
"memory:" "txt"
etc
}
}
},
"Module2": {
"Description": "",
"Layer": "2",
"SourceDir": "pathModule2",
"Attributes": {
"some",
},
"Vendor": "comp",
"components":{
"Component1": {
"path": "something",
"includes": [
"include1",
"include2",
"include3",
"include4",
"include5"
]
"generated:" "txt"
"memory:" "txt"
etc
},
"Component2":{
"path": "something",
"includes": [
"include1",
"include2",
"include3",
"include4",
"include5"
]
"generated:" "txt"
"memory:" "txt"
etc
}
}
},
"Module3": {
"Description": "",
"Layer": "3",
"SourceDir": "path",
"Attributes": {
"some",
},
"Vendor": "",
},
"Module4": {
"Description": "",
"Layer": "4",
"SourceDir": "path",
"Attributes": {
"some",
}
}
}
我必须经历并从中取出一些东西,所以最后我得到了这个:
只要 Vendor 字段等于“comp”,就考虑该模块,考虑它的 SourceDir 字段、所有组件、它们的路径和包含。
所以输出将是:
Module1, "pathModule1", components: [Component1, path, [includes: include1, include2 ,include3 ,include4 ,include5 ]], [Component2, path, includes: [include1, include2 ,include3 ,include4 ,include5 ]]
Module2, "pathModule2", components: [Component1, path, [includes: include1, include2 ,include3 ,include4 ,include5 ]], [Component2, path, includes: [include1, include2 ,include3 ,include4 ,include5 ]]
我真的很难访问我需要的所有字段。
我当前的代码是这样的:
with open ("DB.json", 'r') as f:
modules= json.load(f)
for k in modules.keys():
try:
if swc_list[k]["Vendor"] == "comp":
list_components.append(k)
sourceDirList.append(swc_list[k]['SourceDir'])
for i in swc_list[k]['sw_objects']:
list_sw_objects.append((swc_list[k]['sw_objects']))
except KeyError:
continue
我设法只获得 Module1 和 sourceDir,但没有获得 Component1、2 及其属性.. 我怎样才能做到这一点?
谢谢!
【问题讨论】:
标签: python json attributes