我正在尝试使用python的yaml模块将字符串解析为字典。当值中包含“:”时,我会遇到异常。这是我的示例代码
import yaml
input = '''{"method":"Send", "buf":{"html":"<html><body><div style=\"color:#000; background-color:#fff; font-family:times new roman, new york, times, serif;font-size:12pt\"><ul><li>Sample message</li><li>Parse it<br></li></ul></div></body></html>","text":"\t* Sample message\n\t* Parse it\n"}} '''
yaml.load(input)
我收到以下异常
Traceback (most recent call last):
File "webmailparser.py", line 9, in ?
yaml.load(input)
File "/usr/lib/python2.4/site-packages/yaml/__init__.py", line 58, in load
return loader.get_single_data()
File "/usr/lib/python2.4/site-packages/yaml/constructor.py", line 42, in get_single_data
node = self.get_single_node()
File "/usr/lib/python2.4/site-packages/yaml/composer.py", line 35, in get_single_node
if not self.check_event(StreamEndEvent):
File "/usr/lib/python2.4/site-packages/yaml/parser.py", line 93, in check_event
self.current_event = self.state()
File "/usr/lib/python2.4/site-packages/yaml/parser.py", line 138, in parse_implicit_document_start
StreamEndToken):
File "/usr/lib/python2.4/site-packages/yaml/scanner.py", line 116, in check_token
self.fetch_more_tokens()
File "/usr/lib/python2.4/site-packages/yaml/scanner.py", line 252, in fetch_more_tokens
return self.fetch_plain()
File "/usr/lib/python2.4/site-packages/yaml/scanner.py", line 679, in fetch_plain
self.tokens.append(self.scan_plain())
File "/usr/lib/python2.4/site-packages/yaml/scanner.py", line 1308, in scan_plain
"Please check http://pyyaml.org/wiki/YAMLColonInFlowContext for details.")
yaml.scanner.ScannerError: while scanning a plain scalar
in "<string>", line 1, column 58:
... "html":"<html><body><div style="color:#000; background-color:#ff ...
^
found unexpected ':'
in "<string>", line 1, column 63:
... ":"<html><body><div style="color:#000; background-color:#fff; fo ...
^
Please check http://pyyaml.org/wiki/YAMLColonInFlowContext for details.
有没有解决方法呢?
这有效
import yaml
input = r'{"method":"Send", "buf":{"html":"<html><body><div style=\"color:#000; background-color:#fff; font-family:times new roman, new york, times, serif;font-size:12pt\"><ul><li>Sample message</li><li>Parse it<br></li></ul></div></body></html>","text":"\t* Sample message\n\t* Parse it\n"}} '
print yaml.load(input)