In the process of extracting information from a JSON response text

I'm having trouble extracting specific data from a JSON response. Here is an example of the response structure:

{
   "status": "success",
   "reservations": [
      {
         "id": "22959",
         "subject": "SubjectName1",
         "modifiedDate": "2017-04-03T06:04:24",
         "startDate": "2017-04-03T12:15:00",
         "endDate": "2017-04-03T17:00:00",
         "resources": [
            {
               "id": "17",
               "type": "room",
               "code": "codeName1",
               "parent": {
                  "id": "2",
                  "type": "building",
                  "code": "buildingName1",
                  "name": ""
               },
               "name": ""
            },
            {
               "id": "2658",
               "type": "student_group",
               "code": "groupCode1",
               "name": "groupName1"
            }
         ],
         "description": ""
      },
{
         "id": "22960",
         "subject": "SubjectName2",
         "modifiedDate": "2017-04-04T06:04:33",
         "startDate": "2017-04-04T10:00:00",
         "endDate": "2017-04-04T16:00:00",
         "resources": [
            {
               "id": "17",
               "type": "room",
               "code": "codeName2",
               "parent": {
                  "id": "2",
                  "type": "building",
                  "code": "buildingName2",
                  "name": ""
               },
               "name": ""
            },
            {
               "id": "2658",
               "type": "student_group",
               "code": "groupCode2",
               "name": "groupName2"
            }
         ],
         "description": ""
      }
]
}

My attempts to extract this information using JSON.parse() and for-loops have been unsuccessful. I specifically need to retrieve the subject names, room names, building names, and student group names.

This is how my current code looks:

var getData = {
                "startDate":,
                "endDate":,
                "studentGroup": [
                 ""]
            };



var data = new XMLHttpRequest();
           data.onreadystatechange = function () {             
               if (data.readyState == 4 && data.status == 200) {

                   try {
                       // Parse JSON
                       var json = JSON.parse(data.responseText);
                       // for-loops
                       for (var i = 0; i < json.reservations.length; i++) {
                           for (var x = 0; x < json.reservations[i].length; 
                            x++) { 
                               document.getElementById("test").innerHTML = 
                               json.reservations[i].subject;
                           }
                       }

                   } catch (err) {
                       console.log(err.message);
                       return;
                   }
               }
           };           

            // JSON query
           data.open("POST", "URL", true, "APIKEY", "PASS");
           data.setRequestHeader('Content-Type', 'application/json');
           data.send(JSON.stringify(getData));

Currently, this code only displays the last subject name when there are more than one. How can I adjust it to get all the required data?

Answer №1

After successfully parsing your data, you can completely forget about its JSON origins and treat it as a JavaScript object.

  • Verify the status by accessing data.status to ensure that everything went smoothly.
  • Iterate through data.reservations and within that loop, go through each data.reservations[i].resources.

Answer №2

To extract unique student group names from the parsed data, it is recommended to treat the data as an object. Here's a snippet of code that demonstrates how you can achieve this:

var studentGroups = []; 

for (var i = 0; i < json.reservations.length; i++) {
    if(json.reservations[i].resources != null){
        for(var j = 0; j < json.reservations[i].resources.length; j++){
            var resource = json.reservations[i].resources[j];
            if(resource.type === "student_group"){
                if(studentGroups.indexOf("groupName"))
                    studentGroups.push(resource.name);
                }
            }
        }
    }
}

The output format of the result depends on your specific requirements. It could be a flat array or another JSON structure. You may also need to consider if only the first value is relevant to you. Regardless, this code should give you a starting point on how to handle the task.

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

I'm trying to create a horizontal list using ng-repeat but something isn't quite right. Can anyone help me figure out

Feeling a bit lost after staring at this code for what seems like an eternity. I'm trying to create a horizontal list of 2 image thumbnails within a modal using Angular's ng-repeat. Here's the HTML snippet: <div class="modal-body"> ...

Enhancing the appearance of a Class Component with Material UI using useStyle

I am trying to style the Class Component using useStyle instead of hooks, but I am having trouble figuring out how. Here is my code snippet: import React,{Component} from 'react'; import Avatar from '@material-ui/core/Avatar'; import { ...

Prevent the submit button from being clicked again after processing PHP code and submitting the form (Using AJAX for

I've set up a voting form with submit buttons on a webpage. The form and PHP code work fine, and each time someone clicks the vote button for a specific option, it gets counted by 1. However, the issue is that users can spam the buttons since there i ...

What will be provided as the outcome?

I have recently started learning express.js. The following code snippet is taken from the router library of express.js. var proto = module.exports = function(options) { options = options || {}; function router(req, res, next) { router.handle(req, ...

Convert a list into a JSON format and then append a header to the top of the JSON data

Here is a scenario with a list of objects: List<ScuolaEntity> result = scuolaService.getAllScuoleEntity(); The goal is to convert this list into a JSON object. Attempts have been made using gson, JSONObject, and JsonNode, but adding a header/node to ...

Converting JSON data into XML format with Python

I am looking to convert a large JSON file into an XML file. Here are two lines that I extracted from the JSON file. My goal is to create a root node for every INVENTORY_SEQ_ID found in this file: [{"INVENTORY_SEQ_ID":4577494,"GROUP_NBR":8605548,"SEQ_NBR": ...

Restore original scale ratio to 1:1 following zoom

I am looking for a way to revert the image back to its original zoom level when a button is clicked using the onclick() event. I require the specific code for the onclick() event function. This is the div element in my HTML: div id="zoom"> ...

Using JQuery to delete data from a cookie

I have a delicious cookie that I want to savor before removing one element from it based on the widget ID. if (thisWidgetSettings.removable) { $('<a href="#" class="remove">CLOSE</a>').mousedown(function (e) { ...

Tips for fixing flickering tables and bringing the scrollbar back to the top in your DataTable Forge viewer

Presently, I am working with a DataTable that consists of 100 rows and is being set up using lists. The lists dynamically change based on the selected name from a drop down. To achieve this, I use: $("#datatable").remove(); this.datatable = new Au ...

Press `Enter` to confirm your selection in the BootstrapVue message box input box

Using Vue version v2.6.12 BootstrapVue version v2.21.2 Is there a way to confirm by pressing Enter instead of manually clicking OK? let text this.$bvModal.msgBoxConfirm(<input vModel={text} />) https://i.sstatic.net/7XxOl.png ...

Is there a way to use JavaScript to alter the existing URL?

Currently, I am utilizing a select tag to allow users to choose the number of 'rows' displayed on the table. <%=select_tag :per_page, options_for_select([10,20,50,100]....some more code...., onchange => "if (this.value) {windows.location=& ...

I need to know how to use Axios to fetch data from multiple sources at the same time without any risk of the

Trying to initiate multiple axios operations simultaneously to fetch data from various sources at once using a loop leads to the received data getting intermingled and corrupted. Even creating distinct axios instances for each data source doesn't see ...

Disable the functionality of the next and previous buttons for the Bootstrap carousel when clicking on the outer

Here is the code for the carousel: The next/prev button functions under its respective div, how can I stop it? When I click on the div below the carousel, the carousel continues to move as usual. Below the carousel div, there is another one with a tabbi ...

Trouble with modifying style in Google Chrome and Internet Explorer prior to AJAX request

When utilizing AJAX, I have a common practice of setting up a loading indicator before each request to inform the user about the short wait. Usually, this is achieved by adding an animated loading gif. Interestingly, when performing this action in Firefox, ...

Error: JSON parsing failed due to an expected double-quoted property name in the variable assignment (var json = JSON.parse( xhr.responseText

the JSON file link is provided in the code snippet below SyntaxError: JSON.parse: expected double-quoted property name Javascript: var init = function () { var canv = document.getElementsByTagName("canvas")[0]; var w = canv.clientWidth; var ...

Issue encountered during Heroku deployment: Failed to build React app. When attempting to push changes to Heroku, an unexpected end of input error was received instead of the expected result. This error occurred on an unidentified file at

Encountering a parsing error while attempting to deploy a React app on Heroku using git push heroku master. The app built successfully yesterday, but since then some media queries were added by another contributor to various .scss files. The primary error ...

Restrict the number of dynamic form elements to a maximum of 10 entries

I am working on a feature where users can refer their friends and the data will be saved in a database. <html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <script type='text/javascript' sr ...

Is there a way to ensure that any updates made to the backend database are immediately visible in the browser?

Currently, I am facing an issue with my hardware scanner that is connected to a Windows computer. Whenever I scan an item using the hardware scanner, the Windows computer retrieves the price/information about that specific item. Then, I manually input this ...

Saving integer data retrieved from DynamoDB in a React Native application

I need to store a user's progress by saving a value in a DynamoDB. While storing the value is not difficult, accessing this value for use in my application has proven to be quite challenging. When using dynamoDBWrapper.getItem(params), where the para ...

Unable to insert the string into the database: BaseXException: Name '' is considered invalid

Once I successfully input valid XML from a file into BaseX, how can I now add valid XML from a String? thufir@dur:~/NetBeansProjects/twitterBaseX$ thufir@dur:~/NetBeansProjects/twitterBaseX$ basex BaseX 9.0.1 [Standalone] Try 'help' to get more ...