[javascript] jQuery 'each' loop with JSON array

I'm trying to use jQuery's each loop to go through this JSON and add it to a div named #contentHere. The JSON is as follows:

{ "justIn": [
  { "textId": "123", "text": "Hello", "textType": "Greeting" },
  { "textId": "514", "text":"What's up?", "textType": "Question" },
  { "textId": "122", "text":"Come over here", "textType": "Order" }
  ],
 "recent": [
  { "textId": "1255", "text": "Hello", "textType": "Greeting" },
  { "textId": "6564", "text":"What's up?", "textType": "Question" },
  { "textId": "0192", "text":"Come over here", "textType": "Order" }
  ],
 "old": [
  { "textId": "5213", "text": "Hello", "textType": "Greeting" },
  { "textId": "9758", "text":"What's up?", "textType": "Question" },
  { "textId": "7655", "text":"Come over here", "textType": "Order" }
 ]
}

I'm getting this JSON through use of this code:

$.get("data.php", function(data){

}) 

Any solutions?

This question is related to javascript jquery json each

The answer is


Try (untested):

$.getJSON("data.php", function(data){
    $.each(data.justIn, function() {
        $.each(this, function(k, v) {
            alert(k + ' ' + v);
        });
    });
    $.each(data.recent, function() {
        $.each(this, function(k, v) {
            alert(k + ' ' + v);
        });
    });
    $.each(data.old, function() {
        $.each(this, function(k, v) {
            alert(k + ' ' + v);
        });
    });    
});

I figured, three separate loops since you'll probably want to treat each dataset differently (justIn, recent, old). If not, you can do:

$.getJSON("data.php", function(data){
    $.each(data, function(k, v) {
        alert(k + ' ' + v);
        $.each(v, function(k1, v1) {
            alert(k1 + ' ' + v1);
        });
    });
}); 

This works for me:

$.get("data.php", function(data){
    var expected = ['justIn', 'recent', 'old'];
    var outString = '';
    $.each(expected, function(i, val){
        var contentArray = data[val];
        outString += '<ul><li><b>' + val + '</b>: ';
        $.each(contentArray, function(i1, val2){
            var textID = val2.textId;
            var text = val2.text;
            var textType = val2.textType;
            outString += '<br />('+textID+') '+'<i>'+text+'</i> '+textType;
        });
        outString += '</li></ul>';
    });
    $('#contentHere').append(outString);
}, 'json');

This produces this output:

<div id="contentHere"><ul>
<li><b>justIn</b>:
<br />
(123) <i>Hello</i> Greeting<br>
(514) <i>What's up?</i> Question<br>
(122) <i>Come over here</i> Order</li>
</ul><ul>
<li><b>recent</b>:
<br />
(1255) <i>Hello</i> Greeting<br>
(6564) <i>What's up?</i> Question<br>
(0192) <i>Come over here</i> Order</li>
</ul><ul>
<li><b>old</b>:
<br />
(5213) <i>Hello</i> Greeting<br>
(9758) <i>What's up?</i> Question<br>
(7655) <i>Come over here</i> Order</li>
</ul></div>

And looks like this:

  • justIn:
    (123) Hello Greeting
    (514) What's up? Question
    (122) Come over here Order
  • recent:
    (1255) Hello Greeting
    (6564) What's up? Question
    (0192) Come over here Order
  • old:
    (5213) Hello Greeting
    (9758) What's up? Question
    (7655) Come over here Order

Also, remember to set the contentType as 'json'


Brief code but full-featured

The following is a hybrid jQuery solution that formats each data "record" into an HTML element and uses the data's properties as HTML attribute values.

The jquery each runs the inner loop; I needed the regular JavaScript for on the outer loop to be able to grab the property name (instead of value) for display as the heading. According to taste it can be modified for slightly different behaviour.

This is only 5 main lines of code but wrapped onto multiple lines for display:

$.get("data.php", function(data){

    for (var propTitle in data) {

        $('<div></div>') 
            .addClass('heading')
            .insertBefore('#contentHere')
            .text(propTitle);

            $(data[propTitle]).each(function(iRec, oRec) {

                $('<div></div>')
                    .addClass(oRec.textType)
                    .attr('id', 'T'+oRec.textId)
                    .insertBefore('#contentHere')
                    .text(oRec.text);
            });
    }

});

Produces the output

(Note: I modified the JSON data text values by prepending a number to ensure I was displaying the proper records in the proper sequence - while "debugging")

<div class="heading">
    justIn
</div>
<div id="T123" class="Greeting">
    1Hello
</div>
<div id="T514" class="Question">
    1What's up?
</div>
<div id="T122" class="Order">
    1Come over here
</div>
<div class="heading">
    recent
</div>
<div id="T1255" class="Greeting">
    2Hello
</div>
<div id="T6564" class="Question">
    2What's up?
</div>
<div id="T0192" class="Order">
    2Come over here
</div>
<div class="heading">
    old
</div>
<div id="T5213" class="Greeting">
    3Hello
</div>
<div id="T9758" class="Question">
    3What's up?
</div>
<div id="T7655" class="Order">
    3Come over here
</div>
<div id="contentHere"></div>

Apply a style sheet

<style>
.heading { font-size: 24px; text-decoration:underline }
.Greeting { color: green; }
.Question { color: blue; }
.Order { color: red; }
</style>

to get a "beautiful" looking set of data

alt text

More Info
The JSON data was used in the following way:

for each category (key name the array is held under):

  • the key name is used as the section heading (e.g. justIn)

for each object held inside an array:

  • 'text' becomes the content of a div
  • 'textType' becomes the class of the div (hooked into a style sheet)
  • 'textId' becomes the id of the div
  • e.g. <div id="T122" class="Order">Come over here</div>

My solutions in one of my own sites, with a table:

$.getJSON("sections/view_numbers_update.php", function(data) {
 $.each(data, function(index, objNumber) {
  $('#tr_' + objNumber.intID).find("td").eq(3).html(objNumber.datLastCalled);
  $('#tr_' + objNumber.intID).find("td").eq(4).html(objNumber.strStatus);
  $('#tr_' + objNumber.intID).find("td").eq(5).html(objNumber.intDuration);
  $('#tr_' + objNumber.intID).find("td").eq(6).html(objNumber.blnWasHuman);
 });
});

sections/view_numbers_update.php Returns something like:

[{"intID":"19","datLastCalled":"Thu, 10 Jan 13 08:52:20 +0000","strStatus":"Completed","intDuration":"0:04 secs","blnWasHuman":"Yes","datModified":1357807940},
{"intID":"22","datLastCalled":"Thu, 10 Jan 13 08:54:43 +0000","strStatus":"Completed","intDuration":"0:00 secs","blnWasHuman":"Yes","datModified":1357808079}]

HTML table:

<table id="table_numbers">
 <tr>
  <th>[...]</th>
  <th>[...]</th>
  <th>[...]</th>
  <th>Last Call</th>
  <th>Status</th>
  <th>Duration</th>
  <th>Human?</th>
  <th>[...]</th>
 </tr>
 <tr id="tr_123456">
  [...]
 </tr>
</table>

This essentially gives every row a unique id preceding with 'tr_' to allow for other numbered element ids, at server script time. The jQuery script then just gets this TR_[id] element, and fills the correct indexed cell with the json return.

The advantage is you could get the complete array from the DB, and either foreach($array as $record) to create the table html, OR (if there is an update request) you can die(json_encode($array)) before displaying the table, all in the same page, but same display code.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to each

jQuery animated number counter from zero to value How to iterate over array of objects in Handlebars? Excel VBA For Each Worksheet Loop jQuery looping .each() JSON key/value not working jQuery '.each' and attaching '.click' event How to use continue in jQuery each() loop? jQuery .each() with input elements C++ for each, pulling from vector elements jQuery each loop in table row Get href attribute on jQuery