Problem looping over JSON data returned from URI call

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!

Try using from_json filter

http://docs.ansible.com/ansible/playbooks_filters.html#filters-for-formatting-data

https://gist.github.com/lxhunter/45fb119c0128600158d8

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