Problem looping over JSON data returned from URI call

1,966 views
Skip to first unread message

Andris Bjornson

unread,
Nov 17, 2015, 1:09:30 PM11/17/15
to Ansible Project
Hello - I have a question about looping over json data I’ve received from calling a REST api using the URI module.  I’ve been tearing my hair out over the last several days trying to sort this out…and have googled extensively - but haven’t gotten anywhere.  I think it has to do with the difference between a dict, and array, and a list…but i’m new-ish to ansible and not understanding what i’m doing wrong.  Any help greatly appreciated.

Here is the data returned and registered by the URI module call.  Lets say I registered it in a variable called "registered_variable"  https://gist.github.com/andris/77dcdfd17eef0cdd3563

I can access individual items from the array by doing this:  registered_variable.json.data[1]

I can access attributes of individual items from the array by doing this:  registered_variable.json.data[1].name

But whenever I try to use with_dict or with_items to loop over registered_variable.json.data....I just get an "item is undefined error" (for example)

    - debug:
        msg: "{{item.name}} is the name of the device"
        with_dict: "{{registered_variable.json.data}}"

I also tried first storing the object in a variable first:

    - set_fact:
        devices: "{{ registered_variable.json.data }}"
    - debug:
        msg: "{{item.name}} is the device name"
        with_dict: devices


I am running on the latest dev from checkout (2.0.0)

Any suggestions?

Thanks in advance!

Brian Green

unread,
Nov 18, 2015, 6:32:24 PM11/18/15
to Ansible Project

Andris Bjornson

unread,
Nov 19, 2015, 9:40:28 AM11/19/15
to Ansible Project
Hi Brian - thanks for the reply.

I had found from_json....but then I realized that the uri module is actually putting stuff into an attribute of registered_variable called registered_variable.json.

I did solve my problem, though....it was a bonehead YAML syntax issue with the indents of my with_items statement.

I had:

    - set_fact:
        devices: "{{ registered_variable.json.data }}"
    - debug:
          msg: "{{item.name}} is the device name"
          with_items: devices

When I should have had:

    - set_fact:
        devices: "{{ registered_variable.json.data }}"
    - debug:
          msg: "{{item.name}} is the device name"
      with_items: devices
Reply all
Reply to author
Forward
0 new messages