问题
I have a YAML file where the data contains both strings and integers. When loading YAML file and producing dictionary, YAML "intelligently" makes unquoted integers as type int. Is there any easy way to have YAML treat everything as a string without putting in double quotes around all integers?
Here is a portion of the YAML file:
devices:
rtr1:
reachable: True
instances: [Region-58,]
system_id: 0101.8800.0008
level: Level-2
isis_lsps:
- lsp_id: RTR1CA22CWP.00-00
instance: Region-58
prot_supported: "IPv4, IPv6"
hostname: RTR1CA22CWP
te_router_id: 10.1.0.8
extended_reach:
- ext_reach_id: 0101.8890.0207.00
metric: 10
adm_group: 0x601
local_int_ip: 10.14.2.21
remote_int_ip: 10.14.2.20
max_bw: 400000
max_reserve_bw: 380000
te_metric: 10
After using yaml_load, the numbers are of type "int".
For example, metric: 10
Is there anyway to have yaml_load treat the number 10 as a string without having to put double quotes around it.
回答1:
You can pass the Loader
argument into yaml.load()
like so:
yaml.load(yaml, Loader=yaml.BaseLoader)
This disables automatic value conversion, as BaseLoader
"does not resolve or support any tags and construct only basic Python objects: lists, dictionaries, and Unicode strings." - See reference below
PyYAML Documentation
来源:https://stackoverflow.com/questions/58455861/how-to-read-in-all-yaml-variables-as-strings-using-python