var data = [{"id":10,"name":"sinu"},{"id":20,"name":"shinto"}];
    jQuery(data).each(function(i, item){
        $('#output').append(item.id + ' ' + item.name + '<br>');
    })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output"></div>

var data = [{"id":10,"name":"sinu"},{"id":20,"name":"shinto"}];
jQuery(data).each(function(i, item){
    console.log(item.id, item.name)
})
Answer from Diego ZoracKy on Stack Overflow
🌐
Talkerscode
talkerscode.com › howto › jquery-parse-json-array-of-objects.php
jQuery Parse JSON Array Of Objects - TalkersCode.com
Internally, this jQuery function makes use of the JavaScript JSON.parse() function. $.parseJSON is the abbreviation for this method (). ... It is impossible to parse JSON strings without a string named json. The fundamental goal of utilizing the parseJSON()method seems to be to convert a JSON string into an appropriate JavaScript object.
Top answer
1 of 2
1

Ignoring the calls to your local storage, i have made a simplified example you can use as guide:

// Create the JSON object and stringify

var item1 = {
    item_id:332443,
    item_rank:3.6,
    item_type:["BMW","Camry","Ford"]
};

var item2 = {
    item_id:354443,
    item_rank:2.6,
    item_type:["BMW","Camry","Ford","Tesla","GM","Chevrolet"]
};

var itemsRecords = {
    items:[item1,item2] 
};

var itemsRecordsJSON = JSON.stringify(itemsRecords);

// On document ready, parse the JSON string to object again
// and show their items on the console.

$(document).ready(function()
{
    var records = JSON.parse(itemsRecordsJSON);
    
    records.items.forEach(function(item)
    {
        //console.log(item);
        $("#results").append(
            "<b>Id=" + item.item_id +
            " - Rank=" + item.item_rank +
            " - Type=" + item.item_type.join(",") +
            "</b><hr>"
        );
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="results">
</div>
Run code snippetEdit code snippet Hide Results Copy to answer Expand

2 of 2
0
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>WDV321 Advanced Javascript - JSON</title>
<script
  src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
  integrity="sha256-3edrmyuQ0w65f8gfBsqowzjJe2iM6n0nKciPUp8y+7E="
  crossorigin="anonymous"></script>
  <script src="createJSONArray.js"></script>


<script>
    $(document).ready(function(){
        // get the objects from local storage
        allRecords = localStorage.getItem("studentRecords");
        // convert JSON Object to Javascript object
        var records = JSON.parse(allRecords);
     // add counter
    i =0;
     // add loop to read the objects
    records.students.forEach(function(item)
    {   
     var listAdd = "";
      // create variable to exract the array
        var courses = records.students[i].student_courses;
          // add inner counter
            var j=0;

             $.each( courses, function( ){

              listAdd = listAdd + "<li style = 'margin-left: 80px'>" + courses[j] + "</li>" ;

                 j++;
              courses.join("<br/>") 
});
       $("body").append ("<div class='studentCard'>" + "<h3>Student ID:<span id='id'>" + records.students[i].student_id + "</span></h3>" + "<p>Student GPA:<span id='gpa'>"+ records.students[i].student_gpa +"</span></p>" + "<p>Student Courses:  </p>" + "<ul id = 'classes'></ul>" + listAdd + "</p>" + "</div>" );
     i++;
    });
    });

</script>


<style>
    .studentCard    {
        width:200px;
        box-sizing:border-box;
        background-color:lightblue;
        padding-left:5px;
        padding-top:3px;
        border:thin solid blue;
        box-shadow: 2px 2px 2px grey;
        margin: 5px;
    }

    .studentCard h3 {
        margin:0px; 
    }

 # sort {
  margin-left: 10px;
 }
</style>



</head>

<body>

    <h3>Creating and consuming a JSON object</h3>


</html>
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › JSON › parse
JSON.parse() - JavaScript - MDN Web Docs
3 days ago - The Object, Array, string, number, boolean, or null value corresponding to the given JSON text. ... Thrown if the string to parse is not valid JSON. JSON.parse() parses a JSON string according to the JSON grammar, then evaluates the string as if it's a JavaScript expression.
🌐
W3Schools
w3schools.com › js › js_json_parse.asp
JavaScript JSON.parse()
JS Examples JS HTML DOM JS HTML ... JS Study Plan JS Interview Prep JS Certificate ... The JSON.parse() method converts JSON text into a JavaScript value....
🌐
SitePoint
sitepoint.com › blog › javascript › jquery convert json string to array
jquery convert json string to array — SitePoint
February 12, 2024 - To simply convert json to array, as of jquery 1.4.1 you can do this natively. JSON, or JavaScript Object Notation, is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate. It is often used when data is sent from a server ...
Find elsewhere
🌐
EDUCBA
educba.com › home › software development › software development tutorials › jquery tutorial › jquery json parse
JQuery JSON Parse | How does JQuery JSON Parse Work with example?
April 3, 2023 - The above signature returns a JavaScript object after parsing a well-structured JSON string. The basic purpose of using the parseJSON()method is to transform a JSON string to a corresponding JavaScript object.
Address: Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
jQuery
api.jquery.com › jQuery.parseJSON
jQuery.parseJSON() | jQuery API Documentation
The JSON string to parse. As of jQuery 3.0, $.parseJSON is deprecated.
🌐
Mkyong
mkyong.com › home › jquery › jquery loop over json string – $.each example
jQuery loop over JSON string - $.each example - Mkyong.com
October 14, 2013 - Review a simple jQuery example ... {"id":"4","tagName":"watermelon"}, {"id":"5","tagName":"pineapple"} ]; $.each(json, function(idx, obj) { alert(obj.tagName); });...
Top answer
1 of 10
13

No, with eval is not safe, you can use JSON parser that is much safer: var myObject = JSON.parse(data); For this use the lib https://github.com/douglascrockford/JSON-js

2 of 10
5

I know this is pretty long after your post, but wanted to post for others who might be experiencing this issue and stumble across this post as I did.

It seems there's something about jquery's $.each that changes the nature of the elements in the array.

I wanted to do the following:

$.getJSON('/ajax/get_messages.php', function(data) {

    /* data: 

    [{"title":"Failure","details":"Unsuccessful. Please try again.","type":"error"},
    {"title":"Information Message","details":"A basic informational message - Please be aware","type":"info"}]

    */

    console.log ("Data0Title: " + data[0].title);
    // prints "Data0Title: Failure"

    console.log ("Data0Type: " + data[0].type);
    // prints "Data0Type: error"

    console.log ("Data0Details: " + data[0].details);
    // prints "Data0Details: Unsuccessful. Please try again"


    /* Loop through data array and print messages to console */

});

To accomplish the loop, I first tried using a jquery $.each to loop through the data array. However, as the OP notes, this doesn't work right:

$.each(data, function(nextMsg) {    
    console.log (nextMsg.title + " (" + nextMsg.type + "): " + nextMsg.details);
    // prints 
    // "undefined (undefined): undefined
    // "undefined (undefined): undefined
});

This didn't exactly make sense since I am able to access the data[0] elements when using a numeric key on the data array. So since using a numerical index worked, I tried (successfully) replacing the $.each block with a for loop:

var i=0;
for (i=0;i<data.length;i++){
    console.log (data[i].title + " (" + data[i].type + "): " + data[i].details);
    // prints
    // "Failure (error): Unsuccessful. Please try again"
    // "Information Message (info): A basic informational message - Please be aware"
}

So I don't know the underlying problem, a basic, old fashioned javascript for loop seems to be a functional alternative to jquery's $.each

🌐
GeeksforGeeks
geeksforgeeks.org › how-to-universally-parse-json-into-blocks-using-jquery
How to universally parse JSON into blocks using jQuery ? | GeeksforGeeks
November 18, 2019 - Jquery provides a lot of good features like DOM manipulation, event handling, AJAX support, etc. It is highly recommended to learn the basics of HTML, ... In jQuery, we can update JSON object values dynamically by manipulating the object directly or using utility functions.
Top answer
1 of 2
1

Either change the structure of the JSON so that single components will also be wrapped in an array or adjust convertJson()

function convertJson(data) {
    //...
    $.each(jsondata.license, function(k, lic) {
        var components = lic.component.length ? lic.component : [lic.component];  // <- this

        $.each(components, function(i, comp) { 
            //...
        });
    });
    //...
};

fiddle

2 of 2
0

You have some invalid Json for component element - one time it is a single object, other it is an array of objects. Also some of your code need correction. I have put it all together here:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
                      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head>
    <title>Licenses</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

    <script>
      var jsonData = {
    "@name": "Reuters TV iOS",
    "license": [{
        "@name": "OpenSSL Combined License",
        "component": [{
            "name": "OpenSSL",
            "url": "http://www.openssl.org/"
      }],
        "licensetext": "LICENSE ISSUES \r\n==============\r\n \r\nThe OpenSSL toolkit stays under a dual license, i.e. both the conditions of\r\nthe OpenSSL License and the original SSLeay license apply to the toolkit.\r\nSee below for the actual license texts. Actually both licenses are BSD-style\r\nOpen Source licenses. In case of any license issues related to OpenSSL\r\nplease contact openssl-core@openssl.org.\r\n OpenSSL License \r\n---------------\r\n \r\n==================================================================== Copyright (c) 1998-2008 The OpenSSL Project.  All rights reserved. Redistribution and use in source and binary forms, with or without\r\nmodification, are permitted  provided that the following conditions\r\nare met:\r\n Redistributions of source code must retain the above copyright\r\n   notice, this list of conditions and the following disclaimer.\r\n  Redistributions in binary form must reproduce the above copyright\r\n   notice, this list of conditions and the following disclaimer in\r\n   the documentation and/or other materials provided with the\r\n   distribution. All advertising materials mentioning features or use of this\r\n   software must display the following acknowledgment: \r\n   \"This product includes software developed by the OpenSSL Project\r\n   for use in the OpenSSL Toolkit. (http://www.openssl.org/)\" The names \"OpenSSL Toolkit\" and \"OpenSSL Project\" must not be used to\r\n   endorse or promote products derived from this software without\r\n   prior written permission. For written permission, please contact\r\n   openssl-core@openssl.org. Products derived from this software may not be called \"OpenSSL\" nor may \"OpenSSL\" appear in their names without prior written permission of the OpenSSL Project.  Redistributions of any form whatsoever must retain the following\r\n   acknowledgment: \r\n   \"This product includes software developed by the OpenSSL Project\r\n   for use in the OpenSSL Toolkit (http://www.openssl.org/)\" \r\nTHIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT \"AS IS\" AND ANY\r\nEXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\r\nPURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR\r\nITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\r\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\r\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\r\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\r\nHOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\r\nSTRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\r\nOF THE POSSIBILITY OF SUCH DAMAGE. \r\n====================================================================\r\n \r\nThis product includes cryptographic software written by Eric Young\r\n(eay@cryptsoft.com).  This product includes software written by Tim\r\nHudson (tjh@cryptsoft.com).\r\n &nbsp; Original SSLeay License \r\n -----------------------\r\n Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) \r\nAll rights reserved. \r\nThis package is an SSL implementation written\r\nby Eric Young (eay@cryptsoft.com). \r\nThe implementation was written so as to conform with Netscapes SSL.\r\n \r\nThis library is free for commercial and non-commercial use as long as\r\nthe following conditions are aheared to.  The following conditions\r\napply to all code found in this distribution, be it the RC4, RSA,\r\nlhash, DES, etc., code; not just the SSL code.  The SSL documentation\r\nincluded with this distribution is covered by the same copyright terms\r\nexcept that the holder is Tim Hudson (tjh@cryptsoft.com).\r\n\r\nCopyright remains Eric Young's, and as such any Copyright notices in\r\nthe code are not to be removed. \r\nIf this package is used in a product, Eric Young should be given attribution\r\nas the author of the parts of the library used. \r\nThis can be in the form of a textual message at program startup or\r\nin documentation (online or textual) provided with the package.\r\n Redistribution and use in source and binary forms, with or without\r\nmodification, are permitted  provided that the following conditions\r\nare met:\r\n Redistributions of source code must retain the copyright\r\n   notice, this list of conditions and the following disclaimer.  Redistributions in binary form must reproduce the above copyright\r\n   notice, this list of conditions and the following disclaimer in the\r\n   documentation and/or other materials provided with the distribution. All advertising materials mentioning features or use of this software\r\n   must display the following acknowledgement: \r\n   \"This product includes cryptographic software written by\r\n    Eric Young (eay@cryptsoft.com)\" \r\n   The word 'cryptographic' can be left out if the rouines from the library\r\n   being used are not cryptographic related :-).  If you include any Windows specific code (or a derivative thereof) from\r\n   the apps directory (application code) you must include an acknowledgement:\r\n   \"This product includes software written by Tim Hudson (tjh@cryptsoft.com)\"\r\n \r\nTHIS SOFTWARE IS PROVIDED BY ERIC YOUNG \"AS IS\" AND\r\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r\nARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\r\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\r\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\r\nOR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\r\nHOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\r\nLIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\r\nOUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\r\nSUCH DAMAGE.\r\n \r\nThe licence and distribution terms for any publically available version or\r\nderivative of this code cannot be changed.  i.e. this code cannot simply be\r\ncopied and put under another distribution licence\r\n[including the GNU Public Licence.]"
    }, {
        "@name": "SIL Open Font License 1.1",
        "component": [{
            "name": "Font-Awesome",
            "url": "http://github.com/FortAwesome/Font-Awesome/"
      }],
        "licensetext": "  SIL OPEN FONT LICENSE  Version 1.1 - 26 February 2007  PREAMBLE The goals of the Open Font License (OFL) are to stimulate worldwide\r\ndevelopment of collaborative font projects, to support the font creation\r\nefforts of academic and linguistic communities, and to provide a free and\r\nopen framework in which fonts may be shared and improved in partnership\r\nwith others. The OFL allows the licensed fonts to be used, studied, modified and\r\nredistributed freely as long as they are not sold by themselves. The\r\nfonts, including any derivative works, can be bundled, embedded, \r\nredistributed and/or sold with any software provided that any reserved\r\nnames are not used by derivative works. The fonts and derivatives,\r\nhowever, cannot be released under any other type of license. The\r\nrequirement for fonts to remain under this license does not apply\r\nto any document created using the fonts or their derivatives.  DEFINITIONS \"Font Software\" refers to the set of files released by the Copyright\r\nHolder(s) under this license and clearly marked as such. This may\r\ninclude source files, build scripts and documentation. \"Reserved Font Name\" refers to any names specified as such after the\r\ncopyright statement(s). \"Original Version\" refers to the collection of Font Software components as\r\ndistributed by the Copyright Holder(s). \"Modified Version\" refers to any derivative made by adding to, deleting,\r\nor substituting &mdash; in part or in whole &mdash; any of the components of the\r\nOriginal Version, by changing formats or by porting the Font Software to a\r\nnew environment. \"Author\" refers to any designer, engineer, programmer, technical\r\nwriter or other person who contributed to the Font Software. PERMISSION &amp; CONDITIONS Permission is hereby granted, free of charge, to any person obtaining\r\na copy of the Font Software, to use, study, copy, merge, embed, modify,\r\nredistribute, and sell modified and unmodified copies of the Font\r\nSoftware , subject to the following conditions: 1)  Neither the Font Software nor any of its individual components,\r\nin Original or Modified Versions, may be sold by itself. 2) Original or Modified Versions of the Font Software may be bundled,\r\nredistributed and/or sold with any software , provided that  each copy\r\ncontains the above copyright notice and this license. These can be\r\nincluded either as stand-alone text files, human-readable headers or\r\nin the appropriate machine-readable metadata fields within text or\r\nbinary files as long as those fields can be easily viewed by the user. 3)  No Modified Version of the Font Software may use the Reserved Font\r\nName(s) unless explicit written permission is granted by the corresponding\r\nCopyright Holder. This restriction only applies to the primary font name as\r\npresented to the users. 4)  The name(s) of the Copyright Holder(s) or the Author(s) of the Font\r\nSoftware shall not be used to promote, endorse or advertise any\r\nModified Version, except to acknowledge the contribution(s) of the\r\nCopyright Holder(s) and the Author(s) or with their explicit written\r\npermission. 5)  The Font Software, modified or unmodified, in part or in whole,\r\nmust be distributed entirely under this license, and must not be\r\ndistributed under any other license. The requirement for fonts to\r\nremain under this license does not apply to any document created\r\nusing the Font Software. TERMINATION This license becomes null and void if any of the above conditions are\r\nnot met. DISCLAIMER THE FONT SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\r\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF\r\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT\r\nOF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE\r\nCOPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\r\nINCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL\r\nDAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\r\nFROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM\r\nOTHER DEALINGS IN THE FONT SOFTWARE. "
    }, {
        "@name": "zlib License",
        "component": [{
            "name": "iCarousel",
            "url": "http://github.com/nicklockwood/iCarousel/"
        }, {
            "name": "FXKeychain",
            "url": "http://github.com/nicklockwood/FXKeychain/"
        }, {
            "name": "FXForms",
            "url": "http://github.com/nicklockwood/FXForms/"
        }],
        "licensetext": " The zlib/libpng License Copyright (c) &lt;year&gt; &lt;copyright holders&gt; This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it  and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution."
    }],
    "isProjectComplete": "true"
    };

    function convertJson(jsondata) {
      var output = "<ul>";
      $.each(jsondata.license, function(k, lic) {
        output += '<li>';
        $.each(lic.component, function(k, comp) {
          output += "<b>Name: </b>" + comp.name + " <br /> <b>URL</b> : " + "<a href=' " + comp.url + " '>" + comp.url + "</a>" + " <br />";
        });
        output += "<b>License</b><br /><ul>" + "<div class='license'>" + lic.licensetext + "</div></ul><br />" + "</li>";
      });
      output += "</ul>";
      $("#licenses").html(output);
    };

    $(document).ready( function() {
      convertJson(jsonData);
    });
    </script>
  </head>
  <body>
    <div id="licenses"></div>
  </body>
</html>
Top answer
1 of 3
1

You'll need a list of the properties, in order, since JavaScript object properties are unordered by definition.

With that, it's straightforward:

var props = [
  "current_day", "open_val", "high_val", "low_val", "close_val"
];

var data = [  
   {  
      "current_day":"2011-08-01",
      "open_val":136.65,
      "high_val":136.96,
      "low_val":134.15,
      "close_val":134.15
   },
   {  
      "current_day":"2011-08-02",
      "open_val":135.26,
      "high_val":135.95,
      "low_val":131.50,
      "close_val":131.85
   }
]

var arrays = data.map(
  function (o) {
    var array = [];
    
    props.forEach(
      function (prop)
      {
        array.push( o[prop] );
      }
    );
    
    return array;
  }
);

console.log(arrays);
Run code snippetEdit code snippet Hide Results Copy to answer Expand

Or, for older browsers lacking map() and forEach():

var props = [
  "current_day", "open_val", "high_val", "low_val", "close_val"
];

var data = [  
   {  
      "current_day":"2011-08-01",
      "open_val":136.65,
      "high_val":136.96,
      "low_val":134.15,
      "close_val":134.15
   },
   {  
      "current_day":"2011-08-02",
      "open_val":135.26,
      "high_val":135.95,
      "low_val":131.50,
      "close_val":131.85
   }
]

var arrays = [];

for ( var i = 0; i < data.length; ++i )
  {
    var array = [];
    
    for ( var j = 0; j < props.length; ++j )
      {
        array.push( data[i][props[j]] );
      }
    
    arrays.push(array);
  }

console.log(arrays);
Run code snippetEdit code snippet Hide Results Copy to answer Expand

2 of 3
0

You can try this

You need to map the array, so each new term is the value of each key of the contained object, so:

var stuff = [
   {  
      "current_day":"2011-08-01",
      "open_val":136.65,
      "high_val":136.96,
      "low_val":134.15,
      "close_val":134.15
   },
   {  
      "current_day":"2011-08-02",
      "open_val":135.26,
      "high_val":135.95,
      "low_val":131.50,
      "close_val":131.85
  }
];

var result = stuff.map(function (object) { 
    var arr = [];
  for(var prop in object) {
    arr.push(object[prop]);
  }
  return arr;
});

alert(result);