Python3下YAML转TOML时实现指定格式inline tables输出的问题
解决方案
错误原因
你之前代码的问题在于:仅将外层容器声明为了inline table,但实际需要输出为inline table的Values对应的值仍是普通Python字典,编码器会默认将普通字典识别为普通TOML表格输出,而非inline table格式。
修正后的实现逻辑
需要把需要输出为inline table的字典本身封装为inline table对象,外层结构使用普通Python字典即可,编码时指定TomlPreserveInlineDictEncoder就能正确生成目标格式。
基础示例(输出Values为inline table)
import toml # 要放到inline table里的键值对 kv_dict = {'a':5, 'b':3} # 将键值对封装为inline table对象 inline_table = toml.TomlDecoder().get_empty_inline_table() inline_table.update(kv_dict) # 外层用普通字典即可 result = {"Values": inline_table} # 编码输出 toml_config = toml.dumps(result, encoder=toml.TomlPreserveInlineDictEncoder()) print(toml_config)
输出结果:
Values = { a = 5, b = 3 }
业务场景适配示例(符合你给出的states格式要求)
import toml # 构造需要的inline table对象 outputs_inline = toml.TomlDecoder().get_empty_inline_table() outputs_inline.update({"on": True, "running": False}) inputs_inline = toml.TomlDecoder().get_empty_inline_table() inputs_inline.update({"go": True}) # 构造整体业务结构 config = { "states": { "Started": { "outputs": outputs_inline, "transitions": [ { "inputs": inputs_inline, "target": "Running" } ] } } } # 编码输出 toml_config = toml.dumps(config, encoder=toml.TomlPreserveInlineDictEncoder()) print(toml_config)
输出结果:
[states.Started] outputs = { on = true, running = false } [[states.Started.transitions]] inputs = { go = true } target = "Running"
内容的提问来源于stack exchange,提问作者Mtk59
相关产品推荐
相关产品推荐

