解析带有嵌入式数组的JSON对象,方法

Parsing JSON object with embedded array, how?

本文关键字:JSON 对象 方法 数组 嵌入式      更新时间:2023-09-26

考虑以下Javascript。我正在解析的JSON对象上有一个名为History的数组。History(resp[0]。History)数组中的每个对象都有一个UniqueID属性。请告诉我如何获取数组中每个对象的UniqueID属性?

// Retrieve individual licence information.
function loadLicenceDetails(uniqueID) {
    document.body.style.cursor = 'wait';
    $('#loadingLicenceDiv').modal('show');
    $.ajax({
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        url: '/JadeLicensingWebService/default.asmx/GetLicenceDetails',
        dataType: 'json',
        data: '{"licenceHolder":"' + $.cookie("companyName") + '","uniqueID":"' + uniqueID + '"}',
        success: function (data) {
            resp = $.parseJSON(data.d);
            $('#inputLicenceName').val(resp[0].LicenceName);
            $('#licenceKeyInput').val(resp[0].LicenceKey);
            $('#selectProductType').val(resp[0].Product);
            $('#selectDuration').val(resp[0].Duration);
            $('#startDateInput').val(resp[0].StartDate);
            $('#expiryDateInput').val(resp[0].ExpiryDate);
            $('#orderedByInput').val(resp[0].OrderedBy);
// How do I get at the History.UniqueID ?
            $('#notesInput').val(resp[0].Notes);
            $('#licenceInfoHeader').html('<strong>#' + uniqueID + '</strong> - ' + resp[0].LicenceName);

假设您的JSON看起来像:

{
  "History": [
    {
      "UniqueId": "abc"
    },
    {
      "UniqueId": "def"
    },
    {
      "UniqueId": "ghi"
    },
  ]
}

你可以这样做:

var ids = []; // Make an array to hold the IDs
// Iterate over History items
for (var i = 0; i < resp.History.length; i++) {
  var item = resp.History[i];
  ids.push(item.UniqueId); // Put each ID in the array
}

如果你的JSON对象不是这样的,你能在你的问题中添加一个示例对象,这样你问的问题就更清楚了吗?

使用以下方法解决:

$('#licenceHistoryText').val(resp[0].History[0].DateIssued);

编辑,最终解决方案:

    $.each(resp[0].History, function (i, obj) {
        document.getElementById("licenceHistoryText").value += obj.DateIssued + ' - ' + obj.LicenceName + ' [' + obj.LicenceKey + ']'n';
    });