在Python中迭代嵌套的yaml文档



我有一个嵌套的Yaml,我想遍历并创建一个对象列表。

---
InternalRuleService:
- HomeRules:
- RuleName: Sample1
IgnoreList:
InputParameters:
- resourceId: some-res-id
- ruleAge: 1
- ruleAgeUnits: days
- RuleName: Sample2
IgnoreList:
- Account: '12'
Region: NorthAmericas
- Account: '10'
Region: AsiaPacific
- Account: '10'
Region: Europe
InputParameters:
- InterfaceIds: xxxx1,xxxxx2
- RuleName: Sample3
IgnoreList:
- Account: '14'
Region: NorthAmericas
- Account: '18'
Region: MiddleEast
InputParameters:
- localContact: JohnDoe
contactNumber: 123123 
- CustomRules:
- RuleName: CustomOne
documentType: packet
IgnoreList: 
- Account: '14'
Region: NorthAmericas
- Account: '18'
Region: MiddleEast
ThirdPartyRules:
- RuleName: alta-prism
licenseType: multi
licenseAge: 5
licenseAgeUnit: year
IgnoreList: 
- Account: '45'
Region: NorthAmericas
- Account: '44'
Region: MiddleEast

这是我的代码

import yaml
import json 
with open('rules.yml', 'r') as file:
rules = yaml.safe_load(file)

for rows in rules:
print(rows)

这只给出了输出中的InternalRuleServiceThirdPartyRules。我想遍历所有的homerrules并尝试这个

for rows in rules:
print(rows['HomeRules'])

给了我下面的错误

TypeError: string index必须是整数

这就是我对索引

的尝试
for rows in rules:
print(rows[0])

这将导致I和T被打印在屏幕上。如何访问该文档中的每个条目并从中构建python对象?我想从这个Yaml文件的对象是具有如下属性的对象

RuleName, IgnoreList<LIST>,InputParameters<LIST>,RuleType, subbruletype

此处RuleType将为InternalRuleServiceThirdPartyRules,而subbruletype将为HomeRulesCustomRules,只有在RuleType为InternalRuleService的情况下。忽略

由于HomeRulesCustomRules前面的减号,InternalRuleService成为一个列表,而不是字典。因此,需要使用int型索引。

可以使用pprint:

快速确定
>>> import pprint
>>> pprint.pprint(rules, depth=3)
{'InternalRuleService': [{'HomeRules': [...]}, {'CustomRules': [...]}],
'ThirdPartyRules': [{'IgnoreList': [...],
'RuleName': 'alta-prism',
'licenseAge': 5,
'licenseAgeUnit': 'year',
'licenseType': 'multi'}]}

要从当前的yaml中迭代HomeRules,可以这样做:

for rows in rules['InternalRuleService'][0]['HomeRules']:
print(rows)

打印

{'RuleName': 'Sample1', 'IgnoreList': None, 'InputParameters': [{'resourceId': 'some-res-id'}, {'ruleAge': 1}, {'ruleAgeUnits': 'days'}]}
{'RuleName': 'Sample2', 'IgnoreList': [{'Account': '12', 'Region': 'NorthAmericas'}, {'Account': '10', 'Region': 'AsiaPacific'}, {'Account': '10', 'Region': 'Europe'}], 'InputParameters': [{'InterfaceIds': 'xxxx1,xxxxx2'}]}
{'RuleName': 'Sample3', 'IgnoreList': [{'Account': '14', 'Region': 'NorthAmericas'}, {'Account': '18', 'Region': 'MiddleEast'}], 'InputParameters': [{'localContact': 'JohnDoe', 'contactNumber': 123123}]}

如果你在HomeRulesCustomRules之前删除-,你可以删除列表项索引[0],只写:

for rows in rules['InternalRuleService']['HomeRules']:
print(rows)

最新更新