Unable to read JSON object?

marceloo1223 :

I have am receiving JSON data from an AJAX request in this format:

{
  "details": [{
    "USERID": "45759568",
    "USERNAME": "don",
    "PASSWORD": "don",
    "ISACTIVE": true,
    "USERTYPE": "Admin"
  }]
}

I have tried to read the details object like this, however I am confused whether I am doing things correctly, or making a mess. Any advice would be appreciated.

$(document).on('click', '.loginnow', function() {
  var name = $('.name').val();
  var pass = $('.PASSWORD').val();
  if ($('#Registration').valid()) {
    $.ajax({
      type: "POST",
      url: "@Url.Action("
      DashBoard ","
      Login ")",
      dataType: 'text',
      data: {
        'username': name,
        'password': pass
      },
      success: function(data) {
        debugger
        console.log(data);
        var da = JSON.parse(data);
        da = da.details.USERID; //here da is always undefined
        console.log(da);
        if (da == "") {
          alert("Please Login to Registser");
        } else {
          var userid = da;
          var url = '/AdminPanel/Login?ID=' + userid + '';
        }
      },
      error: function(data) {
        alert('error');
      }
    })
  }
})
Rory McCrossan :

details is an array, so you need to either access it by index (eg. data.details[0].USERID) or loop through it, as in the below example.

Also note that your MVC endpoint will set the correct JSON mime type for the response (assuming you're returning a JsonResult as you should be) so you don't need to manually call JSON.parse().

var data = {
  "details": [{
    "USERID": "45759568",
    "USERNAME": "don",
    "PASSWORD": "don",
    "ISACTIVE": true,
    "USERTYPE": "Admin"
  }]
}

//success: function(data) {
  data.details.forEach(detail => {
    let userid = detail.USERID;
    console.log(userid);

    if (userid == "") {
      alert("Please Login to Registser");
    } else {
      var url = '/AdminPanel/Login?ID=' + userid;
      console.log(url);
    }
  });
//}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=29747&siteId=1