Attempting to extract data from a JSON object within a multidimensional array

Looking at the JSON structure that I need to work with:

[
    {
        "result":"OK",
        "message":"Display",
        "value":200,
        "rows":29
    } , 
    [
        {
            "personID":1,
            "img_path":"/1234/",
            "img":"00001.jpg"
        },
        {
            "personID":2,
            "img_path":"/1234/",
            "img":"00002.jpg"
        },
    ]
]

My goal is to extract ONLY this part:

 personID: 1
 img_path: /1234/
 img: 00001.jpg

Currently, my code retrieves the entire JSON output. Here's a snippet of what I have been doing, which fetches and displays the full JSON response:

var fullURL = the_URL_where_Im_getting_the_json

function readTextFile(file, callback) 
{
    var rawFile = new XMLHttpRequest();
    rawFile.overrideMimeType("application/json");
    rawFile.open("GET", file, true);
    rawFile.onreadystatechange = function() {
        if (rawFile.readyState === 4 && rawFile.status == "200") 
        {
            callback(rawFile.responseText);
        }
    }
    rawFile.send(null);
}

readTextFile(fullURL, function(text){

    var data = JSON.parse(text);
    console.log(data); 
    }
);

Your assistance in helping me retrieve only the specific portion of the JSON data is greatly appreciated. Thank you.

Answer №1

Attempting to retrieve this information using indexes may not be the most reliable method. If you are certain that the structure will remain consistent with this particular type of output, you could destructure the data into info and results and then iterate through them. For instance, if you already know the specific identifier you are searching for, utilizing find can be helpful.

I have expanded on this example to illustrate how functions like map and find can handle larger datasets, especially as your project grows in complexity. Front-end frameworks such as React often automate these processes for you.

const data = [{
    "result": "OK",
    "message": "Display",
    "value": 200,
    "rows": 29
  },
  [{
      "personID": 1,
      "img_path": "/1234/",
      "img": "00001.jpg"
    },
    {
      "personID": 2,
      "img_path": "/1234/",
      "img": "00002.jpg"
    },
  ]
]

const [info, results] = data;
document.getElementById('information').innerHTML = Object.entries(info).map(([key, value]) => `
<div>
  <span class="key">${key.toUpperCase()}:</span>
  <span class="value">${value}</span>
</div>`).join('');

document.getElementById('results').innerHTML = results.map(result => {
  return `<div>ID: ${result.personID}, path: ${result.img_path}</div>`
}).join('');

document.getElementById('find').addEventListener('keyup', function() {
  document.getElementById('target').innerHTML = (results.find(result => result.personID == this.value) || {
    img: 'Not Found'
  }).img
})
.cards {
  display: flex;
}

.card {
  box-shadow: 1px 1px 10px;
  padding: 16px;
  width: 25%;
  margin: 6px;
}

.card-title {
  font-size: 2em;
  border-bottom: 1px solid black;
  padding: 6px 6px 6px 0px;
}

.card-content {
  display: flex;
  flex-direction: column;
  align-items: space-between;
}

.card-content>div {
  margin: 6px;
  display: flex;
  justify-content: space-between;
}

input {
  width: 50px;
}
<div class="cards">
  <div class="card">
    <div class="card-title">
      Information
    </div>
    <div id="information" class="card-content"></div>
  </div>
  <div class="card">
    <div class="card-title">
      All People
    </div>
    <div id="results" class="card-content"></div>
  </div>
  <div class="card">
    <div class="card-title">
      Find IMG
    </div>
    Person ID: 
    <input id="find" />
    <div id="target" class="card-content" />
  </div>
</div>

Answer №2

The information provided in your document seems to require some consistency adjustments.

One way to achieve this is by following these steps:

// To access data of all objects within the 2nd item (data[1][0...n])
var objectData = data[1][0] 
var personID = objectData.personID
var img = objectData.img
var img_path = objectData.img_path

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

Start numerous nodejs servers with just a single command

I currently have multiple Nodejs servers, each stored in its own separate folder within a root directory. Whenever I need to run these servers, I find it cumbersome to navigate through each folder and manually type nodemon *name*. The number of servers i ...

W/System.err: The data in the form of an empty array cannot be converted into a JSONObject due to a org.json.JSONException

Currently, I am working on saving data in a MySQL database. The code snippet for this task is as follows: private void uploadMultipart(final String imageData,final String titolo,final String sottotitolo,final String data) { String tag_string_req ...

Use a JavaScript function on identical IDs

Can someone please help me figure out how to hide multiple divs with the same id using JavaScript? I attempted the following: <script> function filterfunc() { if(document.getElementById('filter_deductible').value == 'id_50'){ ...

Is there a way to incorporate arguments into my discord.js commands?

Hey there! I'm looking to enhance my Discord commands by adding arguments, such as !ban {username}. Any tips or guidance on the best approach for this would be amazing! const Bot = new Discord.Bot({ intents: ["GUILD_MESSAGES", "GUIL ...

Whenever a query is entered, each letter creates a new individual page. What measures can be taken to avoid this?

Currently, I am working on a project that involves creating a search engine. However, I have encountered an issue where each time a user types a query, a new page is generated for every alphabet entered. For instance, typing 'fos' generates 3 pag ...

Leverage the Power of Multiple Markers on Google Maps with API Integration

My project involves creating a WordPress site that displays one marker on a map and has a list of additional locations below it. I aim to remove the description under the map and replace it with a simple list of locations alongside markers on the map. ...

The deletion was not successfully carried out in the ajax request

Can anyone help with an issue I'm having while trying to remove a row from a table using the closest function? The function works fine outside of the $.post request, but it doesn't work properly when used within the post request. Here is my code: ...

Encountering a Node Js post handling error with the message "Cannot GET /url

This is my ejs file titled Post_handling.ejs: <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>POST-Handling Page</title> </head> <body& ...

Is there a way to add zeros at the beginning of ZIP codes that have only 3 or 4 digits using LODASH or Typescript?

Looking at the JSON data below, it includes information on USPS cities, states, counties, latitude, longitude, and zip codes. With over 349,000 lines of data, it's very extensive. ... { "zip_code": 988, "latitude": 18.39 ...

Integrating Material-UI Dialog with Material-table in ReactJS: A Step-by-Step Guide

I have implemented the use of actions in my rows using Material-Table, but I am seeking a way for the action to open a dialog when clicked (Material-UI Dialogs). Is there a way to accomplish this within Material-Table? It seems like Material-UI just appen ...

Shorten a string once a particular word is found in either Smarty or JavaScript/jQuery

I'm currently working on a website and encountering a minor bug related to the addition of content at the end of some strings. For instance: style="background-image:url({$sub.image});" displays style="background-image:url(http://blablalba.fr/phoenix ...

Is it possible to utilize a JavaScript variable in this particular scenario and if so, what is the

let myVariable = <?php echo json_encode($a[i want to insert the JS variable here]); ?>; Your prompt response would be highly valued. Many thanks in advance. ...

Design a model class containing two arrow functions stored in variables with a default value

I am looking to create a model class with two variables (label and key) that store functions. Each function should take data as an input object. If no specific functions are specified, default functions should be used. The default label function will retur ...

AJAX and Python conflict - The requested resource is missing the 'Access-Control-Allow-Origin' header

I am currently developing a unique JavaScript library that has the capability to communicate with a basic Python web server using AJAX. Below is the snippet for the web server class: class WebHandler(http.server.BaseHTTPRequestHandler): def parse_PO ...

Leveraging AJAX and PHP for generating PDF files

My web application is designed to function in a specific way - the user fills out a form, and then using AJAX, the form data is sent to a PHP file that utilizes xpdf to generate a PDF. The goal is for the generated PDF to be easily downloadable on the HTML ...

It is essential for each child in a list to be assigned a unique "key" prop to ensure proper rendering, even after the key has been assigned (in Next

Working with Next JS and implementing a sidebar with custom accordions (created as SideAccord.js component). Data is being looped through an array with assigned keys, but still encountering the following error: Warning: Each child in a list should have a u ...

What is the best way to retrieve the UTC value of a specific date and time within a particular time zone using JavaScript?

I want to create a Date object with a specific time: "Midnight in Los Angeles on Christmas 2011". Although I've used moment.js, which is good, and moment-timezone, which is even better, neither the default Date class nor moment constructors allow for ...

Purge precise LocalStorage data in HTML/JavaScript

How can a specific item in the localStorage be cleared using javascript within an html file? localStorage.setItem("one"); localStorage.setItem("two"); //What is the method to clear only "one" ...

Utilizing Selenium Webdriver to efficiently scroll through a webpage with AJAX-loaded content

I am currently utilizing Selenium Webdriver to extract content from a webpage. The challenge I'm facing is that the page dynamically loads more content using AJAX as the user scrolls down. While I can programmatically scroll down using JavaScript, I a ...

Request for removal in Express.js

Currently in the process of developing a MERN-stack app, but encountering issues with the delete request function. Here is the relevant code snippet: Upon attempting to send a delete request via Postman, an error message is displayed. I have researched ...