Alexandru Vlas Alexandru Vlas - 2 months ago 19
Javascript Question

access the data through json ajax array -> object

I have this json result:

[{
"website": "http://www.rlbuht.nhs.uk",
"sub_type": "Hospital",
"sector": "NHS Sector",
"postcode": "L3 5PS",
"phone": "0151 706 2000",
"partial_postcode": "L3",
"parent_o_d_s_code": "RQ6",
"parent_name": "Royal Liverpool and Broadgreen University Hospitals NHS Trust",
"organisation_type": "Hospital",
"organisation_status": "Visible",
"organisation_name": "Royal Liverpool University Dental Hospital",
"organisation_id": "41513",
"organisation_code": "RQ614",
"longitude": "-2.9669923782348633",
"latitude": "53.408927917480469",
"is_pims_managed": "True",
"fax": "0151 706 5806",
"email": "",
"county": "Merseyside",
"city": "Liverpool",
"address3": "",
"address2": "",
"address1": "Pembroke Place"
}]


And here is my code to access the url and get the json which works fine:

$("#search_hospitals").on('click', function(p_oEvent_search_hospitals) {

var api_search_hospitals, postcode, nhs_hospitals;
p_oEvent_search_hospitals.preventDefault();
postcode = $('#input_nhs_h').val();
api_search_hospitals = 'https://data.gov.uk/data/api/service/health/hospitals/partial_postcode?partial_postcode=' + postcode;

$.ajax(api_search_hospitals, {

complete: function(p_OXHR, p_sStatus) {

nhs_hospitals = $.parseJSON(p_OXHR.responseText);

alert(nhs_hospitals[0].postcode);

}

});
});


I'm just testing with
alert(nhs_hospitals[0].postcode);
to see if I can get the data but I always get
TypeError: undefined is not an object (evaluating 'nhs_hospitals[0].postcode')
...

Can someone please help me in saying what i'm doing wrong, why I'm getting "undefined"? Thank you

To make it easier I did:

complete: function(p_OXHR, p_sStatus) {

nhs_hospitals = $.parseJSON(p_OXHR.responseText);
hospital = nhs_hospitals.result[0];

alert(hospital.postcode);

}

Answer

$('button').on('click', function(p_oEvent_search_hospitals) {

     var api_search_hospitals, postcode, nhs_hospitals;
     p_oEvent_search_hospitals.preventDefault();
     postcode = 'EC1A'
     api_search_hospitals = 'https://data.gov.uk/data/api/service/health/hospitals/partial_postcode?partial_postcode=' + postcode;

     $.ajax(api_search_hospitals, {

         complete: function(p_OXHR, p_sStatus) {

             nhs_hospitals = $.parseJSON(p_OXHR.responseText);
             console.log(nhs_hospitals);
             alert(nhs_hospitals.result[0].postcode);

         }

     });
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>search</button>

This should work. The problem is that the nhs_hospitals object has a result array inside it. If you reference that, you will get your result.