Extracting information from a complicated and unreliable JSON structure

Dealing with a JSON object retrieved via POST query, I am facing the challenge of setting variables due to the varying order of results. This inconsistency is causing issues with my variable assignment based on array positions:

var idle = Example1.results[0].data[1].stats.count;
var waiting = Example1.results[1].data[0].stats.count;

(For instance, this setup works for example 1 but not example 2)

Example1 = {"results":[{"group":{"queueId":"someID"},"data":[{"metric":"oOnQueueUsers","qualifier":"INTERACTING","stats":{"count":2}},{"metric":"oOnQueueUsers","qualifier":"IDLE","stats":{"count":5}}]},{"group":{"queueId":"someID","mediaType":"voice"},"data":[{"metric":"oWaiting","stats":{"count":0}}]}]}

Example2 = {"results":[{"group":{"queueId":"someID","mediaType":"voice"},"data":[{"metric":"oWaiting","stats":{"count":1}}]},{"group":{"queueId":"someID"},"data":[{"metric":"oOnQueueUsers","qualifier":"INTERACTING","stats":{"count":4}},{"metric":"oOnQueueUsers","qualifier":"IDLE","stats":{"count":6}}]}]}

Answer №1

If the order of data is not consistent or if objects have different properties, it's best not to search for specific data in the resultant JSON.

Instead, create a custom data structure to search/index against and then iterate through the JSON, mapping each element to your new structure as needed.

For example:

var exampleResults1 = {
  // example JSON data
}

var newDataSource = {
  parseResults: function(resultObj) {
    // parsing logic here
  }
};

newDataSource.parseResults(exampleResults1);
console.log(JSON.stringify(newDataSource));
Running this code will show you how the new data structure looks after populating it with values from the original JSON object. The keys in the new structure correspond to values from the original data.

This sample code may not cover all data points in your results, but it demonstrates the importance of understanding the returned data and structuring it appropriately based on the actual results.

Answer №2

If you utilize the find() and some() methods, you can achieve the desired outcome.

const example1 = { results: [ { group: { queueId: "someID" }, data: [ { metric: "oOnQueueUsers", qualifier: "INTERACTING", stats: { count: 2 }, }, { metric: "oOnQueueUsers", qualifier: "IDLE", stats: { count: 5 } }, ], }, { group: { queueId: "someID", mediaType: "voice" }, data: [{ metric: "oWaiting", stats: { count: 0 } }], }, ], }; 

const example2 = { results: [ { group: { queueId: "someID", mediaType: "voice" }, data: [{ metric: "oWaiting", stats: { count: 1 } }], }, { group: { queueId: "someID" }, data: [ { metric: "oOnQueueUsers", qualifier: "INTERACTING", stats: { count: 4 }, }, { metric: "oOnQueueUsers", qualifier: "IDLE", stats: { count: 6 } }, ], }, ], };

const idle1 = example1.results
  .find(a => a.data.some(d => d.qualifier === "IDLE"))
  .data.find(b => b.qualifier === "IDLE").stats.count;

const waiting1 = example1.results
  .find(a => a.data.some(d => d.metric === "oWaiting"))
  .data.find(b => b.metric === "oWaiting").stats.count;

const idle2 = example2.results
  .find(a => a.data.some(d => d.qualifier === "IDLE"))
  .data.find(b => b.qualifier === "IDLE").stats.count;

const waiting2 = example2.results
  .find(a => a.data.some(d => d.metric === "oWaiting"))
  .data.find(b => b.metric === "oWaiting").stats.count;

console.log({ idle1 }, { waiting1 }, { idle2 }, { waiting2 });

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

Steps for saving a Pandas dataframe as JSON in UTF-8 format and uploading it back to GitLab to ensure it is interpreted as a CSV format

After successfully reading a CSV using pandas and python-gitlab, I am struggling to get the right structure back into json that can be read as a CSV by gitlab. An example of a CSV file on gitlab showcasing the structure can be seen below: import csv, requ ...

Change the checkbox value to a Boolean before sending it to the Django view

My current project involves developing a Django application featuring a primary dashboard that includes several toggle switches. The objective is to enable users to easily switch their settings on or off, with the changes being automatically saved to the d ...

Incorporate the native Node.js library into your Meteor project

Is there a way to integrate the Natural nodejs library (https://github.com/NaturalNode/natural) into a Meteor project without encountering compatibility issues? Installing Natural using npm within a Meteor project results in errors due to certain aspects ...

Approximately 20% of spoken words are not accurately conveyed by Speech Synthesis Google Voices, failing to adhere to the intended voice selection

When using speechSynthesis.speak(utterance) in Chrome with the "Google UK English Female" voice, there is an issue where a male voice is randomly spoken instead. Any thoughts on how to resolve this? Latest Update: July 26th, 2022 This appears to be a bug ...

What is preventing me from modifying the data in a JSON object?

My task is to update the value "customer.signature", but I am facing an issue with my code. The JSON and HTML seem to be error-free, so the problem lies within my JS code. While "data.signature" updates correctly, "data.customer.signature" does not. The J ...

JavaScript AJAX functions work well when using jQuery, but they may not function properly

Here is the code snippet I am working with: Controller Section def some_method respond_to do |format| format.js { render js: "alert();" } end end JavaScript Section The code above triggers an alert(); jQuery.ajax({ url: url }); However, the ...

Embed a JavaScript file containing PHP code

Recently, I incorporated PHP into my JavaScript code, as shown below: var currentTotalContribution = <?php echo $myContribution; ?>; Now, I am interested in moving that content to my JavaScript file and importing it. I am unsure if this is achievab ...

What is the best approach for finding the xPath of this specific element?

Take a look at this website Link I'm trying to capture the popup message on this site, but I can't seem to find the element for it in the code. Any ideas? ...

How do I create a clean HTML file when using the email editor with TinyMCE?

I was able to develop my own email editor, inspired by this particular example. To enhance user experience, I included a download button at the end of the file so that users can easily retrieve their edited content. The issue I'm facing is that tinym ...

Ways to transfer a v-model from the parent component to a template

I'm currently in the process of designing the user interface for a search page and I want to utilize components to help with code reusability. However, I am facing a challenge in figuring out how to pass the model of the page to the search component. ...

Using a JSON file as a variable in JavaScript

Hello there everyone! I am looking to create a multilingual landing page. The idea is to have a language selection dropdown, and when a language is chosen, JavaScript will replace the text with the corresponding translation from a JSON file. However, I a ...

When a link is added, the Bootstrap drop-down button may become unresponsive

I've encountered an issue with a Bootstrap dropdown menu that I created using jQuery and Bootstrap. The links within the dropdown menu are not redirecting to the correct pages as intended. Can someone help me identify what mistake I might be making he ...

Convert JSON strings with varying formats into objects of a uniform Java class

How can I deserialize JSON strings with different formats into instances of the same Java class using Jackson efficiently? Let's say I have information about users from various sources: Format 1: "user" : { "name" : "John", "age" : 21, ...

What is the best way to link my PHP with MySQL in order to execute an AJAX query?

I am currently working on making this page sortable using a dropdown selection menu. At the moment, there are only two different car makes displayed and they are not sorting properly. My ultimate goal is to enable sorting by make, model, and year, but I ne ...

Rendering user actions instantly in React.js without waiting for server propagation

I am currently developing a shopping list web application where users can toggle items as 'checked' or 'unchecked'. The flow of data in this application is as follows: click on item checkbox --> send database update request --> ...

Saving information to a local file using JavaScript or AngularJS

As a novice in JS development, I am eager to learn how to write data to a file stored in local storage. Within my application, I collect raw data and store it in MongoDB as key-value pairs. Simultaneously, I also wish to save this data to a file in local ...

Creating a controlled state for Formik Material UI React Autocomplete from uncontrolled state

I am currently attempting to understand how to follow the guidelines provided in the documentation for the Autocomplete field of Formik, Material UI, React tool here. The sample code from the documentation is as follows: import { Autocomplete } from &apos ...

What is the best way to synchronize CouchDB with multiple PouchDB instances in an AngularJS application?

I need help with my Angular project. I'm trying to figure out how to sync multiple PouchDB databases to a single CouchDB instance without losing any data. Can anyone provide some guidance or advice? ...

Is an audio player/playlist necessary for showcasing a mix engineer's skills in their

As a newcomer to the world of web development with some background knowledge from school, I work as a mix engineer and have created a portfolio website. Previously, I utilized Soundcloud and Spotify's API to showcase my mixes/songs, but the external J ...

loading xml data into a table partially using jquery

Currently, I am utilizing AJAX to load and parse XML data. I have constructed a table where I am inserting the data from the XML using a loop. The issue lies in the fact that only around 3000 rows are being inserted into the table even though the XML conta ...