如何将具有键值对的字符串转换为字典列表? [英] How to convert a string with key value pairs into a list of dictionaries?

查看:36
本文介绍了如何将具有键值对的字符串转换为字典列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将我的剧本迁移到 ansible 塔式环境.在我的剧本中,我定义了 db_list 之类的变量:

I am trying to migrate my playbooks into ansible tower environment. In my playbook, I defined variables like db_list:

db_list:
   - { dbid: 1, dbname: abc}
   - { dbid: 2, dbname: xyz}

在塔调查中,我可以在调查中输入与 textarea 类似的信息:

in tower survey, I can put similar info as textarea in survey:

dbid: 1, dbname: abc
dbid: 2, dbname: xyz

如何将我的 textarea 数据转换为字典列表?我找不到任何合适的 jinj2 过滤器进行转换.

How can I convert my textarea data into a list of dictionary? I can't find any suitable jinj2 filter for conversion.

我的 ansible 版本是 2.4.

my ansible version is 2.4.

推荐答案

假设 textarea 的内容在一个名为 textarea 的变量中,您可以利用 yaml 非常自由的事实:

Assuming the contents of the textarea are in a variable called textarea, you can take advantage of the fact that yaml is pretty liberal:

- set_fact:
    db_list: >-
      {{ textarea.split("\n") | select | 
         map("regex_replace", "^", "- {") | 
         map("regex_replace", "$", "}") | 
         join("\n") | from_yaml }}

管道中的 select 旨在去除任何空行(因为这些行不是 True-thy)

Where that select in the pipeline is designed to strip off any empty lines (since those lines will not be True-thy)

这篇关于如何将具有键值对的字符串转换为字典列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆