解析逗号分隔项(CommaSeparated)
可以使用 CommaSeparated 验证器验证和解析逗号分隔值。
请注意,解析时默认情况下会删除逗号后的空格。
from strictyaml import CommaSeparated, Int, Str, Map, load, as_document
from ensure import Ensure
int_schema = Map({"a": CommaSeparated(Int())})
str_schema = Map({"a": CommaSeparated(Str())})
解析为 int
a: 1, 2, 3
Ensure(load(yaml_snippet, int_schema)).equals({"a": [1, 2, 3]})
解析为字符串
a: 1, 2, 3
Ensure(load(yaml_snippet, str_schema)).equals({"a": ["1", "2", "3"]})
解析空逗号分隔字符串
a:
Ensure(load(yaml_snippet, str_schema)).equals({"a": []})
无效的 int 逗号分隔序列
a: 1, x, 3
load(yaml_snippet, int_schema)
strictyaml.exceptions.YAMLValidationError:
when expecting an integer
in "<unicode string>", line 2, column 1:
^ (line: 2)
found arbitrary text
in "<unicode string>", line 1, column 1:
a: 1, x, 3
^ (line: 1)
将列表序列化为逗号分隔序列
print(as_document({"a": [1, 2, 3]}, int_schema).as_yaml())
a: 1, 2, 3
将有效字符串序列化为逗号分隔序列
print(as_document({"a": "1,2,3"}, int_schema).as_yaml())
a: 1,2,3
将空列表序列化为逗号分隔序列
print(as_document({"a": []}, int_schema).as_yaml())
a:
将无效字符串序列化为逗号分隔序列
print(as_document({"a": "1,x,3"}, int_schema).as_yaml())
strictyaml.exceptions.YAMLSerializationError:
'x' not an integer.
尝试序列化既不是列表也不是字符串会导致异常
as_document({"a": 1}, int_schema)
strictyaml.exceptions.YAMLSerializationError:
expected string or list, got '1' of type 'int'