今天半天我一直在努力解决这个问题。我已经嵌套了 JSON,我希望能够将每个节点抓取并解析为一个单独的 ol,并以第一个 li 中使用的节点名称作为标题。我可以很好地解析响应并遍历它,但是改变它以将节点分成块是我卡住的地方。到目前为止,这是我的 js:
function parseData(obj) {
var newId = '';
var hashId = '#pay-data';
$.each(obj, function(key, val) {
if(val && typeof val === "object") {
$('#pay-data').append('<ol>');
parseData(val);
} else {
console.log(key + ' - ' + val);
$('#pay-data').append('<li>' + key + ' - ' + val + '</li>');
}
});
}
这是 JSON 的一个示例:
{
"success":true,
"payAndBenefits":{
"employers":[{
"rewards":
{
"totalCompensationValue":1466.95,
"otherDeductions":141.82,
"netPay":605.18,
"incomeTaxes":101,
"governmentReqd":50,
"employerRetirementContributions":90.12,
"employerPaidBenefits":376.83,
"employeeRetirementContributions":102
},
"pay":
{
"paySiteURL":"https://someurl.com",
"payPeriodEnding":"2012-09-30",
"payDate":"2012-10-01",
"otherDeductions":[
{
"description":"G T L Offset",
"amountYTD":45,
"amountThisPeriod":6
},
{
"description":"Before Tax Dent",
"amountYTD":-900,
"amountThisPeriod":-147.82
},
{
"description":"Checking deposit",
"amountYTD":-6668,
"amountThisPeriod":-605.18
}
],
"netPayYTD":6668,
"netPayThisPeriod":605.18,
"incomeTaxesDeductions":[
{
"description":"Federal Income Tax",
"amountYTD":-909,
"amountThisPeriod":-101
}
],
"grossPayYTD":9800,
"grossPayThisPeriod":1000,
"governmentRequiredDeductions":[
{
"description":"Social Security Tax",
"amountYTD":-450,
"amountThisPeriod":-50
}
],
"employeeRetirementPlanContribDeductions":[
{
"description":"401(k)",
"amountYTD":-918,
"amountThisPeriod":-102
}
],
"earnings":[
{
"description":"Regular",
"amountYTD":9000,
"amountThisPeriod":1000
},
{
"description":"Vacation",
"amountYTD":800,
"amountThisPeriod":null
}
]
},
"employerName":"Company Name",
似乎我应该可以在这里某个地方使用 object.name ,但我完全被卡住了。