使用value.Address.City和value.Address.Street怎么样?访问 JSON 数据的最常见方法是通过点表示法。这只是对象名称后跟一个句点,然后是您要访问的名称/属性。http://www.hunlock.com/blogs/Mastering_JSON_%28_JavaScript_Object_Notation_%29
例如,
$.each(data, function(key,value) {
$('#companyDetails').append('<li>'+key+'<span class="ui-li-aside">'+ value.Address.Street + "," + value.Address.City +'</span></li>');
});
对于详细编码,
<html>
<head>
<script src="http://code.jquery.com/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function display(data) {
$.each(data, function(key,value) {
$('#companyDetails').append('<li>'+key+'<span class="ui-li-aside">'+ value.Address.Street + "," + value.Address.City +'</span></li>');
});
}
$(document).ready(function() {
var data = [
{
"Name" : "ABC",
"Company" : "AA Company",
"Address" : {
"Street" : "123 Main Street",
"City" : "Yangon"
}
},
{
"Name" : "DEF",
"Company" : "BB Company",
"Address" : {
"Street" : "8941 Mandalay",
"City" : "NaypiDaw"
}
}
];
display(data);
});
</script>
</head>
<body>
<div id="companyDetails"></div>
</body>
</html>
对于您不知道 json 文件中有哪些数据的情况,
function display(data,flag) {
$.each(data, function(key,value) {
if ($.isPlainObject(value)) {
if(flag == true)
{
$('#companyDetails').append('<b>' + "Company " + (key + 1) + '</b>');
}
display(value,false);
}
else
$('#companyDetails').append('<li>' + key + " : " +'<span class="ui-li-aside">'+ value +'</span></li>');
});
}
在调用显示函数时,
var flag = true;
display(data,flag);
您的输出将是
我希望这会有所帮助。