发布解析JSON

I'm getting a JSON object (I think) back from my AJAX call like this:

$.ajax({
   url: 'testing.php',
            type: 'POST',
            data: {
                code: code_got,
            },
            success: function(data) {
              var list_data = data;
              console.log(list_data);//this is the object shown below
        var list_name = list_data['data']['name'];
        console.log(list_name);//this throws an error that `name` is undefined
            }
          });
});

The response looks like this:

 {
  "total" : 5,
  "data" : [
    {
      "id" : "312464ee1e",
      "stats" : {
        "members" : 58,
      },
      "web_id" : 11966492,
      "name" : "List 1"
    },
    {
      "id" : "312464ee1e",
      "stats" : {
        "members" : 123,
      },
      "web_id" : 1196649,
      "name" : "List 2"
    },

  ]
}

I'm trying to get (first off) the first list name. I've tried this, but it doesn't work:

var list_data = data;
console.log(list_data);//this is the object shown above
var list_name = list_data['data']['name']; //this throw an error "Uncaught TypeError: Cannot read property 'name' of undefined"

Second, I want to do an each to get all of the name items from the data, but I can't get to this until I figure out the JSON structure.

What am I doing wrong here?

You are looking for an object property on an array list_data['data']:

you want a property of an object within that array

Try

var list_name = list_data['data'][0]['name'];

I think you need to add the position within the JSON to the end.

var list_name = list_data['data'][0]['name']

Here's a good tutorial on JSON from W3Schools

First of all you must parse it as json and then loop through it

success: function(data) {
    var lists = JSON.parse(data);
    var dataset = list['data'];
    for(var i=0; i< dataset.length; i++)
        console.log(dataset[i]['name']);
}

Or you can loop through it using $.each:

$.each(dataset, function(index, d){
    console.log(d.name);
});

Also instead of using JSON.parse() you can set the dataType parameter of ajax as 'json' if you know that the returned data is json.

$.ajax({
    ....
    dataType: 'json',
    ....
});

In your JSON, "data" is an array. (simple mistake) The following will log out the value of name. "List 1"

console.log(list_data.data[0].name);

You can parse your data and use $.each function:

For example:

      success: function(data){
           var parsed_data = JSON.parse(data);
            $.each(parsed_data, function(index, value){
                 console.log(jndex, value);
             });
     }