How to split a json key containing a colon into 2 keys

119 views
Skip to first unread message

jean-christophe manciot

unread,
Feb 7, 2020, 11:14:56 AM2/7/20
to Ansible Project
I receive some json data which sometimes start with the first key within "json_data" variable containing a ':', such as:
"json_data": {
    "key1:key2": {
        "key3": [
            "value31",
            "value32",
            "..."
        ]
    }
}

The goal is to split "key1:key2" into 2 keys so that we end up with:
"json_data": {
    "key1": {
        "key2": {
            "key3": [
                "value31",
                "value32",
                "..."
            ]
        }
    }
}

The key names are completely variable so I also have no idea about how to implement the play condition so that this transformation is done only when the first key within "json_data" contains a single colon. 

I am aware that a colon should not be part of any key, but I have no control over that.

Any suggestion?

Vladimir Botka

unread,
Feb 7, 2020, 1:12:40 PM2/7/20
to jean-christophe manciot, ansible...@googlegroups.com
On Fri, 7 Feb 2020 08:14:56 -0800 (PST)
jean-christophe manciot <actionm...@gmail.com> wrote:

> I receive some json data which *sometimes* start with the first key within
> "json_data" variable containing a ':', such as:
> "json_data": {
> "key1:key2": {
> "key3": [
> "value31",
> "value32",
> "..."
> ]
> }
> }
>
> The goal is to split "key1:key2" into 2 keys so that we end up with:
> "json_data": {
> "key1": {
> "key2": {
> "key3": [
> "value31",
> "value32",
> "..."
> ]
> }
> }
> }


Try this

- set_fact:
json_data1: "{{ json_data1|default({})|combine(my_key) }}"
vars:
my_keys: "{{ item.key.split(':') }}"
my_keys_length: "{{ my_keys|length == 1 }}"
my_key: "{{ my_keys_length|
ternary({my_keys[0]: item.value},
{my_keys[0]: {my_keys[1:]|join(':')|default('NA'):
item.value}}) }}"
loop: "{{ json_data|dict2items }}"

HTH,

-vlado

jean-christophe manciot

unread,
Feb 11, 2020, 12:39:06 PM2/11/20
to Ansible Project
I'm impressed. It works perfectly. Only the first key is split as expected..
Reply all
Reply to author
Forward
0 new messages