Parse YAML And Assume A Certain Path Is Always A String
I am using the YAML parser from http://pyyaml.org and I want it to always interpret certain fields as string, but I can't figure out how add_path_resolver() works. For example: The
Solution 1:
From the current source:
# Note: `add_path_resolver` is experimental. The API could be changed.
It appears that it's not complete (yet?). The syntax that would work (as far as I can tell) is:
yaml.add_path_resolver(u'tag:yaml.org,2002:str', ['version'], yaml.ScalarNode)
However, it doesn't.
It appears that the implicit type resolvers are checked first, and if one matches, then it never checks the user-defined resolvers. See resolver.py for more details (look for the function resolve
).
I suggest changing your version
entry to
version: !!str 2.3
This will always coerce it to a string.
Solution 2:
By far the easiest solution for this is not use the basic .load()
(which is unsafe anyway), but use it with Loader=BaseLoader
, which loads every scalar as a string:
import yaml
yaml_str = """\
network:
- name: apple
- name: orange
version: 2.3
old: 2
site: banana
"""
data = yaml.load(yaml_str, Loader=yaml.BaseLoader)
print(data)
gives:
{'network': [{'name': 'apple'}, {'name': 'orange'}], 'version': '2.3', 'old': '2', 'site': 'banana'}
Post a Comment for "Parse YAML And Assume A Certain Path Is Always A String"