最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Parse json array in jquery in foreach loop - Stack Overflow

programmeradmin1浏览0评论

I'm trying to parse json array with objects and use them to create multiple checkboxes. This is what I have:

JSON data:

[{
    "ID": 1,
    "Name": "Bacon",
    "Description": "",
    "Price": 0
}, {
    "ID": 2,
    "Name": "Beef",
    "Description": "",
    "Price": 0
}, {
    "ID": 3,
    "Name": "Chicken",
    "Description": "",
    "Price": 0
}, {
    "ID": 4,
    "Name": "Ham",
    "Description": "",
    "Price": 0
}]

In the JS code I have this:

success: function (data) {
    var objects = JSON.stringify(data);
    for (var key in objects) {
        var checkBox = "<input type='checkbox' data-price='" + key.Price + "' name='" + key.Name + "' value='" + key.ID + "'/>" + key.Name + "<br/>";
        $(checkBox).appendTo('#modifiersDiv');
    };
    $('#addModifiers').modal('show');
}

But the key object doesn't contain any data. My question is how I can do foreach loop and get the data I need and fetch that data in the checkbox properties.

I'm trying to parse json array with objects and use them to create multiple checkboxes. This is what I have:

JSON data:

[{
    "ID": 1,
    "Name": "Bacon",
    "Description": "",
    "Price": 0
}, {
    "ID": 2,
    "Name": "Beef",
    "Description": "",
    "Price": 0
}, {
    "ID": 3,
    "Name": "Chicken",
    "Description": "",
    "Price": 0
}, {
    "ID": 4,
    "Name": "Ham",
    "Description": "",
    "Price": 0
}]

In the JS code I have this:

success: function (data) {
    var objects = JSON.stringify(data);
    for (var key in objects) {
        var checkBox = "<input type='checkbox' data-price='" + key.Price + "' name='" + key.Name + "' value='" + key.ID + "'/>" + key.Name + "<br/>";
        $(checkBox).appendTo('#modifiersDiv');
    };
    $('#addModifiers').modal('show');
}

But the key object doesn't contain any data. My question is how I can do foreach loop and get the data I need and fetch that data in the checkbox properties.

Share Improve this question edited Jul 29, 2021 at 23:35 halfer 20.4k19 gold badges108 silver badges201 bronze badges asked Apr 14, 2014 at 19:42 LazialeLaziale 8,22547 gold badges155 silver badges270 bronze badges 3
  • Why would you stringify before looping? If anything, you want to parse – tymeJV Commented Apr 14, 2014 at 19:45
  • Your data is an array. You should just iterate the array and then refer to data[i].ID, data[i].Name, etc... Also, why are you calling JSON.stringify()? You want it to be a javascript array, not a string. – jfriend00 Commented Apr 14, 2014 at 19:45
  • You need to know what data is in the success handler. If you use jQuery's ajax call properly, it should already be a javascript array and you can just directly iterate it as an array. Step 1, do a console.log(data) to see exactly what it is. – jfriend00 Commented Apr 14, 2014 at 19:48
Add a comment  | 

5 Answers 5

Reset to default 10

Your data should already be a javascript array because you've specified the JSON type for the jQuery Ajax call so it should have already parsed the JSON into javascript. As such, you can just directly iterate it as the array:

success: function (data) {
    for (var i = 0; i < data.length; i++) {
        var checkBox = "<input type='checkbox' data-price='" + data[i].Price + "' name='" + data[i].Name + "' value='" + data[i].ID + "'/>" + data[i].Name + "<br/>";
        $(checkBox).appendTo('#modifiersDiv');
    }
    $('#addModifiers').modal('show');
}

Or, if you want to use jQuery's .each() iterator instead of a for loop, you can do this:

success: function (data) {
    $.each(data, function(key, item) {
        var checkBox = "<input type='checkbox' data-price='" + item.Price + "' name='" + item.Name + "' value='" + item.ID + "'/>" + item.Name + "<br/>";
        $(checkBox).appendTo('#modifiersDiv');
    });
    $('#addModifiers').modal('show');
}

You shouldn't be using var objects = JSON.stringify(data); since the data is already a JSON object.

Use JSON.stringify to create a string from a object

Use JSON.parse is to create an object from a string

Example:

var data = [{id: 1, name:'personsName'}, {id: 2, name:'personsName2'}]
var string = JSON.stringify(data)
var json = JSON.parse(string)

You can loop trough the data and append by using:

data.forEach(function(key, index){
   $("#modifiersDiv")
      .append($("<input></input>")
      .attr("type", "checkbox")
      .attr("data-price",key.Price )
      .attr("name",key.Name )
      .attr("value",key.ID)
      .text(key.Name); 
}

You try to change your json string on json string and not on json object (use JSON.parse to do that).

// You have a string and you want and object : 
var string = "[....]";
var object = JSON.parse(string);

// You have a object and you want and string: 
var object = {...};
var string = JSON.stringify(object);

Or better you can use the type attribut of jQuery ajax function, (put 'json' after your success function and jQuery give you avec object and not a Json string). If you have already do that, you already have an object, so you don't need to update your data

Use

  $.each(data, function(key, value){
      var checkBox = "<input type='checkbox' data-price='" + value.Price + "' name='" + value.Name + "' value='" + value.ID + "'/>" + value.Name + "<br/>";
      $(checkBox).appendTo('#modifiersDiv');
  });
jQuery(document).ready(function () { 
let table_responsive_data_html = "<table class='main-cart-table' id='tblOne'>";
        table_responsive_data_html += '</table>';
        alert(table_responsive_data_html);
});
发布评论

评论列表(0)

  1. 暂无评论