Search code examples
javascriptajaxrequestresponse

Array of arrays json Javascript, ajax response


Im trying to access to parameter value from response.

  $.ajax({
        type: "POST",
        url: "",
        dataType: 'text',
        async: false,
        headers: {
            "Authorization": "Basic " + btoa(username + ":" + password)
        },
        data: '{ "action" : "create", "resource" : {"name" : "teddssssssssddsssdsddddsdddwdsdssdsddi",  "description": "Test Tenant Description","parent": {"href": "localhost"}}}',
        success: function(as) {
            alert(as[0][0]["id"]);          
        }
  });

in the success area i got the response, in json. I want to access to the id value, but i cant. always says undefined, i tried different options. this is the response format.

{
  "results": [
    {
      "href": "localhost/1111111",
      "id": "100000000111",
      "name": "test",
      "ancestry": "1000011111",
      "divisible": true,
      "description": "Test Tenant Description",
      "use_config_for_attributes": false,
      "default_miq_group_id": "10021200000173"
    }
  ]
}

I dont know if i can access direct to the parameter or better get the response as text and split.


Solution

  • The response has a different structure. Your response is an object with one property and value is an array of objects.

    something like {'results': [...{}]}

    Key 0 does not exist.

    const data = {"results":[{"href":"localhost/1111111","id":"100000000111","name":"test","ancestry":"1000011111","divisible":true,"description":"Test Tenant Description","use_config_for_attributes":false,"default_miq_group_id":"10021200000173"}]};
    
    
    console.log(data.results[0].id);