Loop through a JSON-formatted string

I am currently faced with the challenge of passing the MongoDB Query Result in String Format to a JSP Page using Ajax. While I am able to successfully retrieve the data, I am struggling with how to iterate over that data.

Note : The JSON Structure has a Dynamic Schema as shown below

Query Result in String Format

[
{
   "_id":"...",
   "user":"John Doe",
   "hobbies":["1","2","3"],
   "address":{
      "city":"...",
      "state":"...",
      "country":"..."
   },
   "cell":97265xxxxx
},
{
   "_id":"...",
   "user":"John Doe",
   "hobbies":["1","2","3"],
   "cell":97265xxxxx
}
...
]

To tackle this issue, I first convert the JSON String into a JavaScript Object using jQuery's parseJSON() method. However, when attempting to loop over the data, I encounter issues with undefined values.

Below is the code snippet

<button>Click Me</button><br/>
<p id="p0"></p> 
<p id="p1"></p>
<p id="p2"></p>
<p id="p3"></p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> 
<script>
    $(document).ready(function(){
        $("button").on("click",function(){
            $.ajax({
                url:'QuizDemoServlet',
                type:'post',
                success:function(data) {

                    //JSON String is Fetched Successfully
                    $("#p0").html(data);

                    var jso = $.parseJSON(data);
                    alert("JSO " +jso.length);
                    for(var iterate=0; iterate<jso.length; iterate++){
                        $("#p1").append(iterate["user"]+"<br>");
                        $("#p2").append(iterate["hobbies"]+"<br>");
                        $("#p3").append(iterate["cell"]+"<br>");
                    }
                },
                error:function(msg){
                    alert("Error");
                    console.log(msg);
                }
            });
        });
    });
</script>

Answer №1

Assuming that your JSON data is accurate, be sure it follows this structure:

[
 {
   "_id":"...",
   "user":"John Doe",
   "hobbies":["1","2","3"],
   "address":{
      "city":"...",
      "state":"...",
      "country":"..."
   },
   "cell":"97265xxxxx"
 },
 {
  "_id":"...",
  "user":"John Doe",
  "hobbies":["1","2","3"],
  "cell":"97265xxxxx"
 },
......
 {

   .....
 }
]

Before proceeding, validate the JSON using tools like http://jsonlint.com/

The JSON represents an array of objects, which means you can iterate over it easily in JavaScript.

Let's assume that the variable data contains your JSON data.

var data = JSON.parse(YOUR_JSON_STRING); // Remember, your JSON data is a `string` and needs to be `parsed` into a JavaScript object for iteration.

In this scenario, you can loop through the data like so:

for(var obj=0;obj<data.length;obj++){
      // Extract each object here.
      //obj['_id'] 
      // obj['user']
      // Be cautious with dynamic schemas; ensure the key exists before accessing it.

      if(data[obj].hobbies!= undefined){
          //Iterate over hobbies.
      }

      if(data[obj].address!=undefined){
          var city = data[obj].address.city;
          var state = data[obj].address.state;
          var country= data[obj].address.country;
     }
   ....and so on
}

Answer №2

for(let i = 0; i < dataArray.length; i++) { 
   $("#name").append(dataArray[i].name + "<br>");
   $("#hobbies").append(dataArray[i].interests + "<br>");
   $("#phone").append(dataArray[i].phone + "<br>");
}

Functioning correctly

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

Apply CSS styles when the text exceeds the size of the textbox

Is there a way to create a textbox that scrolls on hover only if the text is longer than the textbox itself? Check out my attempt here: https://jsfiddle.net/SynapticError/wqh4ts3n/35/ The text should scroll on hover if it's longer than the textbox. ...

Extracting data from subsequent page using XHR request

Looking to extract data from the second page of reviews for this user: 1happykat. The challenge lies in triggering the XHR request that is initiated by clicking the next button. Even though it can be observed using Chrome developer tools, replicating it i ...

Ways to create dynamic functionality with JavaScript

I need to iterate through the document.getElementById("b") checked in a loop. Is this achievable? How can I implement it? <img class="img-responsive pic" id="picture" src="images/step1.png"> <?php //get rows query ...

Converting DataSet to JSON using ServiceStack.Text

I'm facing an issue with serializing a dataset to JSON using ServiceStack.Text (from Nuget.org). I'm currently working with the version 4.0.50 and VS 2015. The error message that keeps popping up is: Process is terminated due to StackOverflowE ...

Getting an HTML element by its ID that was passed from the ng-init directive in Angular can be achieved

When I use ng-click, I am able to retrieve the html element by id. However, when I use ng-init, I only get null. Please take a look at my codepen here. HTML Code: <script type="text/javascript"> var memId = "bb7de28f-0f89-4f14-8575-d494203acec7 ...

Attempting to serialize a form using Ajax and jQuery

I am facing an issue with submitting user input from a modal using jQuery and AJAX. The problem is that the AJAX call is not capturing the user input. Even though the AJAX call is successful, when I check on the server side, the user input appears to be bl ...

Methods for adding a line to an array

I am currently working on a loop where I need to populate my array called photos: $scope.photos = []; var str = data.data.Photos; var res = str.split('|'); angular.forEach(res, function (item) { ...

When no files are uploaded, req.files.upload.length will return zero; however, if more than one file is uploaded, it will return the total number of files. In the

When using this loop, the variable “req.files.upload.length” will return the file count if 0 or more than one files are uploaded. However, it returns the file size if only one file is uploaded. Why does this happen? This is the upload handler: app.po ...

What's the best way to retrieve a value from a function that invokes itself multiple times?

My task involves navigating through nested object data to find a specific result. I am using the findByKey function, which recursively calls itself until the desired result is found. However, instead of returning object.source, I am getting undefined. as ...

Click on the button to reveal the hidden content within the div, and then smoothly scroll down to view

I have a footer div that is present at the bottom of every page on our site. I've added a button to expand this div, but I'm looking for a way to automatically scroll the page down so that the user can view the expanded content without manually s ...

There was an issue with rendering: "TypeError: Unable to access the 'name' property of an undefined object" [Vue alert]

I encountered the following error message: TypeError: Cannot read property 'name' of undefined Here's the snippet from the Vue file where the error occurred: <tr v-for="user in fields.data" :key="user.id"> <td>{{ user.id ...

I am receiving a success message from webpack indicating that the compilation was successful, but I am encountering a blank page in the

My app.js looks like this: import Home from "./pages/home/Home"; import Login from "./pages/login/Login"; import Profile from "./pages/profile/Profile"; import Register from "./pages/register/Register"; import { Brow ...

The child module invokes a function within the parent module and retrieves a result

Guardian XML <tr [onSumWeights]="sumWeights" > Algorithm sumWeights(): number { return // Calculate total value of all weights } Offspring @Input() onTotalWeights: () => number; canMakeChanges() { return this.onTota ...

Dynamic Lookup Material Table

I am currently using MaterialTable imported from "material-table". import MaterialTable from "material-table" I am attempting to make the 'lookup' for an editable table dynamic. My goal is to have a drop-down with edit options when I make change ...

How can I modify the parent form element to only evaluate the expression at the text node, without affecting Angular interpolation?

Currently, I am in the process of developing an eCommerce platform and utilizing angular to construct a widget on product detail pages. Unfortunately, my control over the initial HTML rendered for the browser is quite limited. While most tasks related to m ...

Comparing timestamps in JavaScript and PHP - what are the discrepancies?

I seem to be having an issue with the inconsistency in count between two timestamps. Upon page load, I set the input value as follows: $test_start.val(new Date().getTime()); //e.g. equal to 1424157813 Upon submitting the form via ajax, the PHP handler sc ...

jQuery fadeIn effect happening at rapid speed

I am currently working on integrating ajax with WordPress. After the ajax call is completed, I am successfully fading out a specific div slowly. However, when trying to fade in the new data using jQuery's fadeIn() method, I noticed that regardless of ...

A function similar to setCell for modifying form fields in JqGrid

After searching through numerous answers from @Oleg, I couldn't find the solution I was looking for. I am dealing with a grid where I can edit inline in certain fields. Specifically, I am working with autocomplete functionality and when I select an it ...

A compilation of web browsers and their compatible versions for the SVG engine

I recently encountered an issue with the org chart I created using getorgchart. Everything was running smoothly until I tested it on IE8. It turns out that getorgchart relies on the SVG engine for rendering, which is not supported by IE8. I attempted to ...

Combining PHP with JSON encoding to power a dynamic and interactive data table

I am utilizing a jQuery plugin known as DataTables, which necessitates a JSON string to be returned for table rendering. At present, the outputted JSON appears like this (check out the aaData array): {"sEcho":0,"aaData":[[{"ID":"1","idPatient":"122342"," ...