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

What could be the reason for the 'tsc' command not functioning in the Git Bash terminal but working perfectly in the command prompt?

I recently installed TypeScript globally on my machine, but I am facing an issue while trying to use it in the git bash terminal. Whenever I run tsc -v, I encounter the following error: C:\Users\itupe\AppData\Roaming\npm/node: l ...

Attempting to transfer various variables from several windows using AJAX

Is it possible to pass multiple variables from two different windows into the same PHP script? If not, what would be the best approach to take? Thank you. verifyemail.html <script type = "text/javascript" src = "js/js_functions.js"></script> ...

Implementing Vue modal within a Laravel 5.2 foreach loop

I am facing a challenge with my Laravel blade template that uses a foreach loop to create a table with data. Each row has a link that triggers a modal when clicked. However, the issue is that clicking on any link activates the modal for every row instead o ...

How can Firebase-RealtimeDatabase be configured to allow for user registration and login?

To enable Android users to register and log in through my app, I have configured the permissions for .read and .write as true. However, this has made the user JSON file accessible to anyone since it is public. How can I restrict access to the database on ...

I'm curious if it's possible to utilize Raspberry Pi GPIO pins within a JavaScript frontend

Is it possible to utilize Raspberry Pi's GPIO pins in Javascript? Specifically, I am interested in reading the values of the Raspberry Pi PIR sensor without having separate Python and Javascript applications. Ideally, I would like a solution that inte ...

"What could be the reason for web3.eth.getAccounts() method returning an empty array when used with console.log

Upon executing web3.eth.getAccounts().then(console.log);, I encountered an empty array and also received a warning stating ./node_modules/web3-eth-accounts/src/scrypt.js Critical dependency: the request of a dependency is an expression. The project began w ...

Utilizing v-for in Vue with TypeScript to generate multiple checkboxes

My goal was to capture the values of checkboxes and store them in an array using v-model. However, I encountered an issue where the first time I toggle a checkbox, it doesn't register. Only after checking a second box and hitting submit does the secon ...

The keys within a TypeScript partial object are defined with strict typing

Currently, I am utilizing Mui components along with TypeScript for creating a helper function that can generate extended variants. import { ButtonProps, ButtonPropsSizeOverrides } from "@mui/material"; declare module "@mui/material/Button&q ...

PHP warning: Notice: Offset not defined

After creating an API to retrieve data from a database and display it as JSON in HTML, I encountered some PHP errors while trying to echo the data: Notice: Undefined offset: 80 in /opt/lampp/htdocs/ReadExchange/api.php on line 16 Notice: Undefined offse ...

Using AngularJS to compare values against user input to determine if they are greater or lesser

When a user inputs data into an input field, it must fall within the range of values retrieved from the database. The value entered by the user should meet either the minimum, maximum, or default value obtained from the database. For instance, if the minim ...

broadcast updated $rootScope

How do I update the $rootScope.$broadcast with a new value? Let's take a look at this code snippet: var test = "fisk"; if(angular.element(this).hasClass('monster')) { var monster_info = angular.element(this).find("img").attr("title"); ...

Ways to update the DOM once a function has been executed in VUE 3 JS

I'm working on implementing a "like" or "add to favorite" feature in VUE 3. However, I'm facing an issue where the UI doesn't update when I like or unlike something. It only refreshes properly. I'm using backend functions for liking and ...

What is the best way to link labels with input fields located separately in Angular?

Imagine a scenario where labels and form fields are being created in a *ngFor loop, as shown below: app.component.ts export class AppComponent { items = ['aaa', 'bbbbbb', 'ccccccccc'] } app.component.html <div class ...

Is there a workaround in TypeScript to add extra details to a route?

Typically, I include some settings in my route. For instance: .when('Products', { templateUrl: 'App/Products.html', settings: { showbuy: true, showex ...

Rails issue: Active Model Serializer searching for incorrect serializer

Every time I try to use the create method, it throws a NameError at me. Failure/Error: post :create, { user: { email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c4a7aca5b6a8a1b784a1bca5a9b4a8a1eaa7aba9">[email ...

Angular component injected with stub service is returning incorrect value

While attempting to write tests for my Angular component that utilizes a service, I encountered an issue. Despite initializing my userServiceStub property isLoggedIn with true, the UserService property appears false when running the tests. I experimented ...

What is the process of directing to another HTML page within the same Express controller script?

I am looking to switch the initial page (login page) to a second page (admin dashboard) from within the same controller in Express after a specific action has been taken. Here is the relevant code snippet from my controller file nimda.js: function handle ...

Leverage the power of Angular CLI within your current project

I am currently working on a project and I have decided to utilize the angular cli generator. After installing it, I created the following .angular-cli file: { "$schema": "./node_modules/@angular/cli/lib/config/schema.json", "project": { "name": " ...

A customizable and adaptable Tetris-inspired CSS design perfect for any screen size

If we imagine having a block like this: <div class="block"></div> There are different sizes of the block: <div class="block b1x1"></div> <div class="block b2x1"></div> <div class="block b1x2"></div> For i ...

"Exploring the process of making a REST call from an Angular TypeScript client to

I'm currently developing a Sessions Server for a project at work. My dilemma lies in the fact that I'm struggling to find resources on how to make JavaScript HTTP calls from a server running with http.createServer() and server.listen(8080, ...) ...