parsing a nested json file

161 views
Skip to first unread message

Dader Grund

unread,
Jul 11, 2016, 9:17:47 AM7/11/16
to Ansible Project
hallo,

i have a  nested json file like :
{
        "fw1": {
                "ipv4": {
                        "rtr": {
                                "ip": "1.2.3.4",
                                "net": "1.2.3.4",
                            
                        }
                }
        },
        "fw2": {
                "ipv4": {
                        "rtr": {
                                "ip": "4.3.2.1",
                                "net": "4.3.2.1",
                               
                        }
                }
        }
}


How could i parse in this case only the "ip" value of "fw2" ?
for a non nested json dictionary this phrase has worked for me

{{ (lookup('file', '/etc/foo.txt') | from_json).get('ip') }}.


Kai Stian Olstad

unread,
Jul 11, 2016, 11:41:45 AM7/11/16
to ansible...@googlegroups.com
from_json)['fw2']['ipv4']['rtr']['ip'] }}

or

{{ (lookup('file', '/etc/foo.txt') | from_json).fw2.ipv4.rtr.ip }}

--
Kai Stian Olstad

Dader Grund

unread,
Jul 11, 2016, 1:16:57 PM7/11/16
to Ansible Project, ansible-pr...@olstad.com
Thanks alot dude. It did work ^^
i have recently got it working using lookup('file', '/etc/foo.txt') | from_json).get('fw2').get('ipv4').get('rtr').get('ip')     # haha though  it didn't look quit  pretty
i noticed if i am using an attribute with a minus sign i.e "fw2-m" the dot notation wouldn't work.
Just curious how could one overcome this issue?

Kai Stian Olstad

unread,
Jul 11, 2016, 1:50:14 PM7/11/16
to ansible...@googlegroups.com
Python identifiers is not allowed to have dash in them(because dash is a
subtraction), so only way around it in Ansible, is to use the square
brackets notation.

--
Kai Stian Olstad

Dader Grund

unread,
Jul 12, 2016, 7:51:56 AM7/12/16
to Ansible Project, ansible-pr...@olstad.com
can u please tell me why should one add a single parentheses to "from_json).foo" ?
Reply all
Reply to author
Forward
0 new messages