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

"react commands" are not recognized as an internal or external command by any program or batch file

Initially, everything was working smoothly until I decided to download some updates from the git repository. However, upon execution, I encountered an error message stating that "react scripts" are not recognized as an internal or external command, operabl ...

Unlocking the Potential of JavaScript Proxy: Clearing Out an Array Object

Examining the JavaScript Proxy code snippet below: const queue = new Proxy([], { get: (target, property) => { return target[property]; }, set: (target, property, value) => { target[property] = value; this._pro ...

Managing custom types in hashtable serialization and deserialization using ASP.NET

I'm trying to send a hashtable through a post request, but in order to do that I need to convert the hashtable to json format. Currently, I am utilizing Newtonsoft JSON.NET for this task. Hashtable ht = new Hashtable(); User u = new User(); u.name = ...

Is it possible to redefine a function that is attached to $ctrl outside of the AngularJS framework?

Within my DOM, there exists an element containing ng-click="$ctrl.goToHome(), which is connected to the logo on my site. This particular element is generated by a third-party AngularJS application. The complete element can be seen below: <img ng-if=":: ...

Update object properties in Angular controller dynamically

Take a look at my simple plunker Within the code, I am attempting to link a scope variable to an object property. $scope.name = 'World'; var obj = { "name":$scope.name } $scope.$watch('name', function(){ console.log(obj["name"]); ...

Experiencing issues while attempting basic private key encryption with the Node crypto library

Currently, I am in the process of creating a quick proof of concept (POC) to encrypt an incoming string using a standard key. Below is the code snippet from my middleware: import Crypto from 'crypto'; export default async function encrypt(req, r ...

The model `user` does not have a primary key attribute specified. It is required for all models to have a primary key attribute defined

I have defined a waterline model below: var Waterline = require('Waterline'); var bcrypt = require('bcrypt'); var User = Waterline.Collection.extend({ identity: 'user', datastore: 'myMongo', autoPK: false, attribut ...

Using target="_blank" does not seem to open a popup window in React

The issue is that the target="_blank" attribute is not working properly for the modal popup window. Instead, the link is opening in the same page and the popup is closing. <TermLink to="/legal/privacy-policy" target="_blank"> Privacy Pol ...

The integration of Vue JS is not displaying properly in an Electron application

My electron app is loading Vue JS 2 from my local machine, but when I attach my el to an element, it completely empties the element and replaces its contents with a Vue JS comment. What could be causing this issue? index.html <!DOCTYPE html> <htm ...

Retrieve recently appended DOM elements following the invocation of createComponent on a ViewContainerRef

I have a current function in my code that dynamically creates components and then generates a table of contents once the components are added to the DOM. This service retrieves all h3 elements from the DOM to include in the table of contents: generateDy ...

Load remote JSON data into WordPress Advanced Custom Fields through the backend

I have a custom post type called "Products" and I am using the ACF (Advanced Custom Fields) plugin with this post type. The fields group in ACF includes: - One field named 'Product Description' as a text area - Three text fields named 'Feat ...

React Redux - There is an error during rendering as expected props have not been received yet

After retrieving data from an API and storing it in the Redux state, I utilize a helper function within mapStateToProps to filter and modify a portion of that data before passing it along as props. Although everything appears to be functioning correctly b ...

Setting parameters to Labels in Objective-C it is important to have unique

As someone new to iOS Programming, I have encountered an issue with assigning values to labels. Below is the data I receive from a service: ( { EmpName = Peter; Relation = SouthAfrica; }, { EmpName = Smith; Relation = WestIndies; }, { ...

How can Material UI React handle long strings in menu text wrapping for both mobile and desktop devices?

Is there a way to ensure that long strings in an MUI Select component do not exceed the width and get cut off on mobile devices? How can I add a text-wrap or similar feature? Desktop: https://i.sstatic.net/lo8zM.png Mobile: https://i.sstatic.net/8xoW6. ...

Ways to execute a script from termly on NextJS using JSX

I've been utilizing termly to assist in creating legal terms for a website I'm developing. They provided me with some HTML containing a script, but I am struggling to get it to execute on a page in JSX. I attempted to use both Script and dangerou ...

Modify the classname of two element class i

I am trying to change the class on click within an <i> element that has 2 classes. The first class is always "fa" and the second class can be either "fa-minus" or "fa-plus". I need to toggle between "minus" and "plus" based on the current class. Ca ...

Is there a lack of a feature for automatically shifting to the next input element in dynamically-created HTML?

I have a JavaScript function that is triggered when a user clicks a button: htmlstring = ''+ '<div class="input_holder">'+ '<div class="as_input_holder"><input tabindex="1" class="as_input form-control-sm ...

PHP Array Element Output

After making a call to the Twitter API, I have received an Array of data containing the "Top 10 Trending" items. However, I am facing difficulty in printing out the individual elements such as names. Below is the code snippet that I have been using to disp ...

Displaying a loading progress bar while the website is being loaded using Javascript

Currently working on developing a GUI site, I am looking to implement a progress bar. However, I require some JavaScript code that can detect the loading status of the site along with the number of elements/images that have been loaded so far, as well as d ...

jQuery shorthand conditional statements

I currently have a jQuery function that is triggered by two separate buttons. $("#btnSearch, #btnDirectorSearch").click(function () { The construction of the HTML output within this function relies on which button was clicked. To accomplish this, I am ut ...