As a beginner in JS programming, I have a question that may seem trivial. Despite hours of searching online, I haven't been able to find a solution that works for me.
I am dealing with multiple JSON feeds where each URL provides a multilayer JSON record like the examples below:
yields:
{ "LGICUS01OperationResponse": { "ca": { "ca_phone_mobile": "07799 123456", "ca_request_id": "01ICUS", "ca_return_code": 0, "ca_dob": "11.07.1950", "ca_last_name": "Pandy", "ca_num_policies": 0, "ca_phone_home": "01962 811234", "ca_email_address": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="65244b3504...">', "ca_house_name": "", "ca_policy_data": "", "ca_customer_num": 1, "ca_first_name": "Andrew", "ca_house_num": "34", "ca_postcode": "PI101OO" } } }
yields:
{ "LGICUS01OperationResponse": { "ca": { "ca_phone_mobile": "123", "ca_request_id": "01ICUS", "ca_return_code": 0, "ca_dob": "30.09.1965", "ca_last_name": "Tracey", "ca_num_policies": 0, "ca_phone_home": "", "ca_email_address": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0c5e49...>', "ca_house_name": "Tracey Island", "ca_policy_data": "", "ca_customer_num": 2, "ca_first_name": "Scott", "ca_house_num": "", "ca_postcode": "TB14TV" } } }
My goal is to extract the user information from these JSON records and manipulate them as an array for later use. The desired format is shown below:
{
"rows":[
{"ca_customer_num":1", "ca_first_name:"Andrew",...}
{"ca_customer_num":2", "ca_first_name:"Scott",...}
...
]
}
Here is the code snippet I've been working on:
<!DOCTYPE html>
<html>
<head>
<title>JSON test</title>
<script src="jquery.js" type="text/javascript"></script>
<script>
var myjson = [];
for (i = 1; i < 11; i++) {
getCurrentJson(i);
console.log(myjson[i].LGICUS01OperationResponse.ca.ca_phone_mobile);
}
function getCurrentJson(current){
$.ajax({
dataType: "json",
url: "http://192.49.208.193:9081/ci/c/"+current,
success: function(data){
myjson[current] = data;
console.log(myjson[current]);
console.log(myjson[current].LGICUS01OperationResponse.ca.ca_phone_mobile);
}
});
}
</script>
</head>
<body>
</body>
</html>
While the console outputs within the ajax function display the Object information and phone numbers correctly, the initial console output in the loop throws an error "Uncaught TypeError: Cannot read property 'LGICUS01OperationResponse' of undefined(…)". Do I need to convert data types or make any other adjustments? I also attempted to pass the myjson array to the getCurrentJson function but it didn't work.