Storing numerous JSON records into an array by parsing them from a file

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.

Answer №1

It's important to remember that AJAX requests are asynchronous

Note: see the partial example provided below (also keep in mind that not all requests have to be successful, some may fail and never reach done == total)

var myjson = [];
var total = 10;
var done = 0;

for (i = 1; i <= total; i++) {
  getCurrentJson(i);
  // at this point AJAX request haven't finished (most likely)
  //console.log(myjson[i].LGICUS01OperationResponse.ca.ca_phone_mobile);
}

function allDone() {
  console.log(myjson);
}

function getCurrentJson(current){
  $.ajax({ 
    dataType: "json",
    url: "http://192.49.208.193:9081/ci/c/"+current,
    success: function(data){
      myjson[current] = data;
      done++;
      console.log(myjson[current]);
      console.log(myjson[current].LGICUS01OperationResponse.ca.ca_phone_mobile);
      if (done == total) {
        allDone();
      }
    }
  }); 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Answer №2

Have you ever noticed that Javascript is asynchronous, requiring you to wait for a response before continuing? It can be frustrating when your code executes before the ajax request has completed.

console.log(myjson[i].LGICUS01OperationResponse.ca.ca_phone_mobile);

If you want to prevent this issue, consider using async or handling callbacks appropriately in your code.

Check out this example on CodePen: http://codepen.io/anon/pen/gLPJNe

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to alter formData using jQuery

For my form submission using AJAX, I utilize FormData to gather data. Here is how I collect the form's data: var data = new FormData($(this)[0]); One of the inputs on the form consists of a color value in HSV format that I need to convert to hex. Wh ...

I am looking to view all products that belong to the category with the ID specified in the request, and have red-colored stocks

Within my database, I have defined three mongoose models: Product, Category, and Stock. The Product model contains two arrays - categories and stocks, each including respective category and stock ids. My goal is to retrieve all products where the category_ ...

What are the steps to utilize chrome.tabs.onUpdated.addListener?

I am currently working on a Chrome extension where I need to display an alert() showing the page URL whenever the user switches tabs or enters a new URL in a tab. However, my current implementation is not functioning as expected: chrome.tabs.onUpdated.ad ...

Pressing the reset button on the search box triggers a JQuery and HTML function

I am new to this, so bear with me. I've simplified my styling for easy pasting here, but the concepts still apply. I have a list of items, a working search field, and functioning filter buttons. What I want is for the filter buttons to reset to &apos ...

Exploring AngularJS: Utilizing limitTo and filter

I'm having some trouble with using angular's limitTo and filter together. I want to search for a value in the search box, then apply a limit to the number of results displayed by entering a number in the filter box and clicking apply filter. Howe ...

Utilizing Angular 5: Enhancing ngFor with a Pipe and a Click Event

Iterating through an array of objects using *ngFor, I apply various filters via pipes to manipulate the resulting list. One of these pipes relies on a user input from a search field. Upon clicking on one of the ngFor elements, the corresponding object is p ...

Ways to retrieve the user's IP address and provide the information in JSON format

Although I am not an expert in PHP, I specialize in developing Android apps. One of the challenges I face is extracting the user's IP address from a specific URL . This URL provides various information when accessed, but my main requirement is to retr ...

Move a pin on Mapbox

I have a question regarding my map markers: https://i.sstatic.net/2HndV.png Currently, the center of the blue markers align with my desired coordinates. Is there a way to adjust the markers slightly upwards so that the tip sits exactly on my specified po ...

When running collection.find().toArray(callback) in node.js with mongodb, the result is coming back

When I run my code, mydocuments.find({}).toArray is returning empty. I have seen some solutions posted but they don't apply to my situation since I am using MongoClient.connect. Any help would be greatly appreciated. var MONGOHQ_URL="mongodb://harish ...

Transform the image data retrieved from an external API into the appropriate format for displaying on the webpage

When I make a call to an external API, it returns image data that I want to render on my page. However, the response looks like this when I log it to the console: https://i.stack.imgur.com/GpDhH.png I'm not very familiar with image formats, so I&ap ...

Difficulties arise when working with Json data and performing searches using a for-each

Utilizing an API that returns data in JSON format, which I believe is referred to as "pairs". Apologies if my terminology is incorrect. I am then parsing through the JSON response to locate a specific user ID, which happens to be the second value in each ...

Retrieving an array of various responses using Axios

My current code includes a function that retrieves exchange rates for various stocks: export const getRates = (symbole1, symbole2, symbole3) => { const res = [] axios.all([ axios.get(`${baseUrl}/${symbole1}`), axios.get(`${ ...

Please input new items by clicking a button

I have a dilemma with handling an array of objects in my Vue component. I am using v-for to display the objects, but now I want to update certain items in the array and save only those changes in a new object. Currently, when I attempt this by mapping over ...

Tips for effectively utilizing the useDraggable and useSortable hooks within the dnd-kit library

I'm currently working on developing a basic calculator using React and dnd-kit. The idea is to have draggable elements in the calculator that can be sorted within a droppable area with smooth animation effects. However, I've encountered an issue ...

Issue while rendering Vuex

Currently in the process of setting up a project using Vuex and Vue, I have encountered a peculiar issue. It seems to be related to the order of rendering, but despite multiple attempts to modify the code, the problem persists. My approach involved access ...

I need to access a directory that is outside of my current folder in Express.js

I have two folders within my main folder; one is for front-end and the other is for back-end. project ├── back-end │ ├── public │ └── routes │ ├── Calling.js │ └── index.js └── front-end ├ ...

Falling rain animation in JavaScript

I'm a beginner in the world of JavaScript and I'm trying to create a div on a webpage with a rain effect. I've managed to generate random blue points within the div, but I'm struggling to make them move downwards. Here's the code I ...

Ways to automatically check a checkbox using jQuery

Is there a way to use jQuery to programmatically click a checkbox? I am trying to create a hidden checkbox that will be checked when a user clicks on a specific element, but my current code is not functioning as expected and I am unsure why. You can view ...

Utilizing Ajax to send IP addresses and obtain location data

Is there a website or webpage that can be used to input a user's IP address and receive their country or location as plain text? Below is a code snippet demonstrating how I attempted to retrieve the user's IP address: I inserted the following c ...

Organize every rectangle and text element in D3 into distinct groups

Currently, I am working on creating a bar graph using d3.js. The goal is to display text on top of each bar when the user hovers over it. To achieve this, the <text> and <rect> elements need to be grouped inside a <g> element. For Exampl ...