使用Ansible从JSON响应中提取字段

分段故障

我有一个任务,它对页面执行GET请求。响应的主体是类似于以下内容的JSON。

 {
  "ips": [
    {
      "organization": "1233124121",
      "reverse": null,
      "id": "1321411312",
      "server": {
        "id": "1321411",
        "name": "name1"
      },
      "address": "x.x.x.x"
    },
    {
      "organization": "2398479823",
      "reverse": null,
      "id": "2418209841",
      "server": {
        "id": "234979823",
        "name": "name2"
      },
      "address": "x.x.x.x"
    }
  ]
}

我想提取字段ID和地址,并尝试(对于ID字段):

tasks:
  - name: get request                                           
    uri:
      url: "https://myurl.com/ips"
      method: GET
      return_content: yes
      status_code: 200
      headers:
        Content-Type: "application/json"
        X-Auth-Token: "0010101010"
      body_format: json
    register: json_response 


  - name: copy ip_json content into a file
    copy: content={{json_response.json.ips.id}} dest="/dest_path/json_response.txt"

但是我得到这个错误:

字段“ args”具有无效值,该值似乎包含未定义的变量。错误是:“列表对象”没有属性“ id”。

哪里有问题?

康斯坦丁·苏沃洛夫(Konstantin Suvorov)

错误是:“列表对象”没有属性“ id”

json_response.json.ips 是一个列表。

您可能需要选择一个元素(第一): json_response.json.ips[0].id

或者,如果需要所有ID,请使用mapjson_query过滤器处理此列表

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章