我想在python中解析yaml文件。我的hosts.yaml文件如下:
access:
host: abc
hostUrl: url-for-abc
bearerToken: jjlhlj
expires: someDate
host: xyz
hostUrl: url-for-xyz
bearerToken: kdsddh
expires: someDate
我解析yaml的python代码如下:
import yaml
def parse():
with open('hosts.yaml', 'r') as hosts_file:
hosts = yaml.load(hosts_file)
for host, val in hosts["access"]["host"]:
print host
print host["hostUrl"]
print host["bearerToken"]
parse()
我收到以下错误:
python parse_yaml.py
Traceback (most recent call last):
File "parse_yaml.py", line 19, in <module>
parse()
File "parse_yaml.py", line 13, in parse2
hosts = yaml.safe_load(hosts_file)
File "/usr/lib64/python2.7/site-packages/yaml/__init__.py", line 93, in safe_load
return load(stream, SafeLoader)
File "/usr/lib64/python2.7/site-packages/yaml/__init__.py", line 71, in load
return loader.get_single_data()
File "/usr/lib64/python2.7/site-packages/yaml/constructor.py", line 37, in get_single_data
node = self.get_single_node()
File "/usr/lib64/python2.7/site-packages/yaml/composer.py", line 36, in get_single_node
document = self.compose_document()
File "/usr/lib64/python2.7/site-packages/yaml/composer.py", line 55, in compose_document
node = self.compose_node(None, None)
File "/usr/lib64/python2.7/site-packages/yaml/composer.py", line 84, in compose_node
node = self.compose_mapping_node(anchor)
File "/usr/lib64/python2.7/site-packages/yaml/composer.py", line 133, in compose_mapping_node
item_value = self.compose_node(node, item_key)
File "/usr/lib64/python2.7/site-packages/yaml/composer.py", line 84, in compose_node
node = self.compose_mapping_node(anchor)
File "/usr/lib64/python2.7/site-packages/yaml/composer.py", line 127, in compose_mapping_node
while not self.check_event(MappingEndEvent):
File "/usr/lib64/python2.7/site-packages/yaml/parser.py", line 98, in check_event
self.current_event = self.state()
File "/usr/lib64/python2.7/site-packages/yaml/parser.py", line 428, in parse_block_mapping_key
if self.check_token(KeyToken):
File "/usr/lib64/python2.7/site-packages/yaml/scanner.py", line 116, in check_token
self.fetch_more_tokens()
File "/usr/lib64/python2.7/site-packages/yaml/scanner.py", line 220, in fetch_more_tokens
return self.fetch_value()
File "/usr/lib64/python2.7/site-packages/yaml/scanner.py", line 576, in fetch_value
self.get_mark())
yaml.scanner.ScannerError: mapping values are not allowed here
in "hosts.yaml", line 3, column 12
我无法理解,如果yaml文件结构与代码有些问题是错误的。 提前谢谢。
答案 0 :(得分:2)
您不能同时拥有字符串和对象作为键的值。你可以做字符串
access:
host: abc
host: xyz
或对象
access:
host:
hostUrl: url-for-abc
bearerToken: jjlhlj
expires: someDate
host:
hostUrl: url-for-xyz
bearerToken: kdsddh
expires: someDate
但不是两者
access:
host: abc
hostUrl: url-for-abc
bearerToken: jjlhlj
expires: someDate
host: xyz
hostUrl: url-for-xyz
bearerToken: kdsddh
expires: someDate
我建议你将主机的名称放在对象的name
键中
access:
host:
name: abc
hostUrl: url-for-abc
bearerToken: jjlhlj
expires: someDate
host:
name: xyz
hostUrl: url-for-xyz
bearerToken: kdsddh
expires: someDate