Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract field from JSON response with Ansible

I have a task which performs a GET request to a page. The response's body is a JSON like the following.

 {
  "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"
    }
  ]
}

I want to extract the fields id and address, and tried (for id field):

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"

but I get this error:

the field 'args' has an invalid value, which appears to include a variable that is undefined. The error was: 'list object' has no attribute 'id'..

Where is the problem?

like image 414
SegFault Avatar asked Mar 24 '17 15:03

SegFault


People also ask

How do I access JSON response data?

To access the JSON object in JavaScript, parse it with JSON. parse() , and access it via “.” or “[]”.

How do you parse a string of JSON response?

Example - Parsing JSONUse the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}'); Make sure the text is in JSON format, or else you will get a syntax error.

How can we extract JSON data?

To extract the name and projects properties from the JSON string, use the json_extract function as in the following example. The json_extract function takes the column containing the JSON string, and searches it using a JSONPath -like expression with the dot . notation. JSONPath performs a simple tree traversal.


1 Answers

The error was: 'list object' has no attribute 'id'

json_response.json.ips is a list.

You either need to choose one element (first?): json_response.json.ips[0].id.

Or process this list for example with map or json_query filters if you need all ids.

like image 65
Konstantin Suvorov Avatar answered Oct 15 '22 13:10

Konstantin Suvorov