Decoding JSON data with JavaScript

My JavaScript code is giving me trouble. I am using an ajax method that returns a JSON string like this:

{
  "ObjectResponse": {
    "Operation": "OK",
    "Response": "SUCCESS",
    "Message": "List of AAA Found",
    "List": [
      {
        "keySource": "gat\/images\/images_set\/apple.jpg",
        "idSiteKey": "1",
        "text": "Apple"
      },
      {
        "keySource": "gat\/images\/images_set\/cat.jpg",
        "idSiteKey": "2",
        "text": "Cat"
      },
      {
        "keySource": "gat\/images\/images_set\/coffee.jpg",
        "idSiteKey": "3",
        "text": "Coffee"
      },
      {
        "keySource": "gat\/images\/images_set\/dog.jpg",
        "idSiteKey": "4",
        "text": "Dog"
      },
      {
        "keySource": "gat\/images\/images_set\/horse.jpg",
        "idSiteKey": "5",
        "text": "Horse"
      },
      {
        "keySource": "gat\/images\/images_set\/police.jpg",
        "idSiteKey": "6",
        "text": "Police"
      },
      {
        "keySource": "gat\/images\/images_set\/tree.jpg",
        "idSiteKey": "7",
        "text": "Tree"
      }
    ]
  }
}

I am trying to assign the content like this:

xhr.onreadystatechange = ensureReadiness; 
....
responseText = xhr.responseText;

When I attempt to parse it in JavaScript with:

response = JSON.parse(responseText);

If I try to access a property like

response.ObjectResponse.Operation
, I get the correct content.. but accessing the List always breaks.

Interestingly, if I use the same JSON string and directly assign it to a variable without calling the service, I can access the List successfully.

var myTemporalString ='{"ObjectResponse":{"Operation":"OK","Response":"SUCCESS","Message":"List of Keys Found","List":...';
response.JSON.parse(myTemporalString);

Any suggestions on why this might be happening?

Answer №1

One approach you might consider is as follows:

    xhr.onreadystatechange = function() {
                if (xhr.readyState == 4) {
                    if (xhr.status == 200) {

                        try{
                                var jsonData = JSON.parse(xhr.responseText);
                            }catch(error){
                                console.log(error);
                                alert(error);
                                return;
                            }

                        for(let i=0; i<jsonData.ObjectResponse.List.length; i++){
                                   console.log(jsonData.ObjectResponse.List[i].text);
                                 console.log(jsonData.ObjectResponse.List[i].keySource);
                                   console.log(jsonData.ObjectResponse.List[i].idSiteKey);
                           }

              }
           }
       }

Answer №2

Employ a loop for efficient iteration!

let items = responseObject.arrayOfItems;
let length = items.length;
for(index=0; index<length; index++) {
    //Access individual items using items[index]
    items[index].keyValue
    items[index].siteIDKey
    items[index].description
}

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

Can you explain the meaning behind this TypeScript variable declaration syntax?

Can anyone explain the meaning of this code snippet: myCollection: Collection|any = null; I'm having trouble understanding it... Does it indicate that myCollection is set to type Collection, (which is an interface), with a default value of null? But ...

Issue with Panel Settings and Tooltip in Amcharts

Looking for solutions to two specific issues that I am struggling with: I have two charts with multiple panels, each having only one scroll bar. My problem lies with the balloon text - when hovering over a balloon, I need to display two different texts ...

Regular expressions - For alphanumeric or numeric with a possible slash character included

I need assistance with extracting alphanumeric values from a string array using RegEx. For instance: Apartment 101/B First Villa 3324/A Second Milk 12MG/ML Third Sodium 0.00205MG/ML Fourth Water 0.00205MG Fifth Eggs 100 Sixth My goal is to retrieve the v ...

Converting Gson to JSON with Node.js: A step-by-step guide

Can anyone suggest a method to convert gson data to json data in node js? Here is a sample gson data: ["test","{\"ID\":0}] ...

A step-by-step guide on enabling Autoclick for every button on a webpage

I am currently using Jquery and Ajax to carry out an action, my goal is for a code to automatically click on every button once the page has finished loading. Although I attempted to use the following javascript code to achieve this at the end of my page, ...

What is the best way to utilize multiple Ajax requests in order to generate server-side response data?

There are two separate Ajax queries that retrieve different parts of the required server-side data for DataTables. The first query retrieves 40 rows of records as a JSON string from a table, while the second query simply returns the total count for the tab ...

Update information with a fresh GET call - React Dropdown

I have implemented a Dropdown Menu using MUI that allows users to select a specific day value. I would like the menu to trigger a new GET request with the updated parameter whenever the selection changes. However, I am unsure how to achieve this since it u ...

Identifying the Click Event Within an ngx Bootstrap Modal

I recently set up an ngx bootstrap modal using the instructions provided in this helpful guide - . However, I'm facing a challenge in detecting click events within the modal body once it's open. Below is the code snippet from my app component. D ...

When you find that the plugins on pub.dev do not offer web support, consider utilizing npm packages for Flutter web development

I am currently working on developing a cross-platform app using Flutter for iOS, Android, and web. However, some plugins do not support web. Fortunately, I came across npm packages that provide the same functionality and I am considering integrating them. ...

Using knockoutjs to call a component on the home page

I am currently facing some challenges with knockoutjs components, as I am following the guidance provided in the official knockout component documentation. Could someone please advise me on how to correctly invoke my widget component on the main page? It ...

Navigating through a collection of elements

I am currently working on my Stripe Checkout Session, attempting to pass an array of product data to the backend node.js server and iterate over it. The object of products I have is structured like this: { products: [ { _id: '62129d518468 ...

Guide to importing scoped styles into a <NextJS> component

When importing a CSS file, I usually do it like this: import './Login.module.css'; In my component located at components/login/index.js, I define elements with classes such as <div className="authentication-wrapper authentication-basic ...

Creating unique border-radius for each point in a Highcharts column chart with React

Let's flip the script and start at the finish line. My goal is to customize my column chart to resemble this design: https://i.stack.imgur.com/FckJB.png Creating this style is a breeze with chart.js Credit: I've already delved into this inquiry ...

Guide on how to create a custom response using class-validator in NestJS

Is it feasible to customize the error response generated by class-validator in NestJs? The default error message structure in NestJS looks like this: { "statusCode": 400, "error": "Bad Request", "message": [ { "target": {} ...

Discover the combobox element and its value can be easily achieved by using Selenium's find_element_by_xpath method

I am having trouble setting a value in a combobox using selenium. The find_element_by_xpath statement is failing to locate the combobox by class or ng-model. Specifically, I am attempting to change the time period for a stock from one day to one week. Her ...

Flickering effects in THREE.js using Frame Buffer Objects

I've encountered a strange flickering issue while working on a THREE.js scene that involves using a Frame Buffer Object. The flickering disappears when I comment out the line: mesh.material.uniforms.fboData.value = renderTargetA.texture. THREE.FBO ...

The Plupload internal version seems to be incorrect. The file is labeled as 2.3.9, however, the actual version within the file is 2.3

We recently identified a security vulnerability issue with plupload 2.3.6 being deemed as vulnerable. To address this, we downloaded version 2.3.9 from the official Plupload website here: Upon inspection, we found that the zip file is labeled as 2.3.9, bu ...

Setting up the Firebase emulator: should you use getFirestore() or getFirestore(firebaseApp)?

After delving into the process of connecting your app to the Firebase emulators like Firestore emulator, I came across the primary documentation which outlined the steps for Web version 9: import { getFirestore, connectFirestoreEmulator } from "fireba ...

Fixing My Code with JQuery Tabs and Hyperlinking

I have come across a problem while using multiple pages with jQuery tabs. Let's consider Page1.html with #tab1 and #tab2, and Page2.html with #tab3 and #tab4. Here are the issues I am facing: 1) Within the tab content of Page1.html#tab2, there is a h ...

Encountering an issue with compiling Angular due to a Type Inference error

interface Course { name: string; lessonCount: number; } interface Named { name: string; } let named: Named = { name: 'Placeholder Name' }; let course: Course = { name: 'Developing Apps with Angular', lessonCount: 15 }; named = ...