getJSON() will also parse the JSON for you after fetching, so from then on, you are working with a simple Javascript array ([] marks an array in JSON). The documentation also has examples on how to handle the fetched data.

You can get all the values in an array using a for loop:

$.getJSON("url_with_json_here", function(data){
    for (var i = 0, len = data.length; i < len; i++) {
        console.log(data[i]);
    }
});

Check your console to see the output (Chrome, Firefox/Firebug, IE).

jQuery also provides $.each() for iterations, so you could also do this:

$.getJSON("url_with_json_here", function(data){
    $.each(data, function (index, value) {
        console.log(value);
    });
});
Answer from kapa 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
1 week 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....
Find elsewhere
🌐
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.
🌐
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 ...
🌐
jQuery
api.jquery.com › jQuery.parseJSON
jQuery.parseJSON() | jQuery API Documentation
The JSON string to parse. As of jQuery 3.0, $.parseJSON is deprecated.
🌐
Stack Overflow
stackoverflow.com › questions › 45227823
Parse JSON Object to Array using JQuery - Stack Overflow
**And I am calling the API using JQuery with the following method:** var dbImpl = { load: function (loadOptions) { return $.getJSON('http://localhost:777/employee/testjson'); }, }; EXPECTED RESULT I want the result having multiple object array: (I want the result labelled "1", currently the result is labelled "2")
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

🌐
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); });...
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-convert-json-string-to-array-of-json-objects-using-javascript
Convert JSON String to Array of JSON Objects in JavaScript | GeeksforGeeks
December 4, 2024 - The below approaches can be utilized to JSON stringify an array of objects.Table of ContentUsing JSON.stringify with a Replacer Function Using a C ... A map in JavaScript is a set of unique key and value pairs that can hold multiple values with only a single occurrence. Sometimes, you may be required to convert a map into an array of objects that contains the key-value pairs of the map as the values of the object keys.
🌐
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