用钥匙中的点分界符解析山药
我们使用YAML配置进行服务缩放。通常情况下它是这样的:
service:
scalingPolicy:
capacity:
min: 1
max: 1
因此,使用基本的PyyAml和解析很容易获得config ['service'] ['scaleingpolicy'] ['logites'] ['scaping'] ['min']
结果AS 1
。问题是,某些配置是用点定界符构建的:
service.scalingPolicy.capacity:
min: 1
max: 1
此配置的基本消费者是Java的弹簧,并且以某种方式被视为上述示例。但是,由于还需要使用Python解析这些配置 - 我将整个点分离为config ['service.scalingpolicy.capacity']
键。
问题是 - 我将如何使Python解析任何类型的键组合(均由DOTS
隔开 code>表格和:)。我没有找到python yaml libs的相关参数(我已经检查了标准的pyyaml和ruamel.yaml
),并且手动处理任何可能的组合似乎是一个疯狂的想法。我唯一可能的想法是写自己的解析器,但也许我缺少一些东西,所以我不必重新发明自行车。
We use YAML configuration for services scaling. Usually it goes like this:
service:
scalingPolicy:
capacity:
min: 1
max: 1
So it's easy to open with basic PyYAML and parse as an dict to get config['service']['scalingPolicy']['capacity']['min']
result as 1
. Problem is that some configs are built with dots delimiter e.g:
service.scalingPolicy.capacity:
min: 1
max: 1
Basic consumer of this configs is Java's Spring and somehow it's treated equally as the example above. But due to need to also parse these configs with Python - I get whole dot separated line as a config['service.scalingPolicy.capacity']
key.
The question is - how would I make python parse any kind of keys combinations (both separated by dots
and separated by tabulation and :
). I didn't find related parameters for Python YAML libs (I've checked standard PyYAML and ruamel.yaml
) and handling any possible combination manually seems like a crazy idea. The only possible idea I have is to write my own parser but maybe there is something I'm missing so I won't have to reinvent the bicycle.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这不是微不足道的
将递归中的点变成嵌套的数据结构。在这里你有一个嵌套
数据结构和不同的
[键]
查找意味着不同的事物在不同的级别。
如果您在默认的往返模式下使用
ruamel.yaml
,则可以添加一个类变量对于代表映射的类型,该映射定义了键分开的内容和实例变量
这可以跟踪已经匹配的前缀:
它给出:
This is not trivial, it is much more easy to split a lookup with a key with
dots into recursing into a nested data structure. Here you have a nested
data structure and different
[key]
lookups mean different thingsat different levels.
If you use
ruamel.yaml
in the default round-trip mode, you can add a class-variableto the type that represents a mapping, that defines on what the keys were split and an instance variable
that keeps track of the prefix already matched:
which gives:
我发现了使用Pyyaml的替代溶液。该策略是用“ k1.k2.k3:value”的格式将dict转换为字符串,然后将其转换为dict。可能不是最有效的,但它有效。
I have found an alternative solution with pyyaml. The strategy is convert the dict into a string with the format "k1.k2.k3: value" and then convert it into a dict. Probably not the most efficient, but it works.