遍历和打印嵌套的JSON数据 [英] Traverse and print nested JSON data
本文介绍了遍历和打印嵌套的JSON数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个嵌套格式的JSON数据文件.我想遍历这些数据并以JQuery listview的形式输出,但无法做到这一点.
I have a file with JSON data in a nested format. I want to traverse through this data and output it in the form of a JQuery listview but am unable to do so.
JSON数据采用以下格式:
The JSON data is in this format:
{
"Name":"A",
"Company": "B",
"Address": {
"Street":"ABC",
"City":"XYZ"
}
}
我尝试了以下操作:
$.each(data, function(key,value) {
$('#companyDetails').append('<li>'+key+'<span class="ui-li-aside">'+value+'</span></li>');
});
但这不会正确输出地址"块.
but this does not output the 'Address' block properly.
推荐答案
我不知道这是否是最有效的方法,但我认为它可以满足您的要求.
I don't know if this is the most efficient way of doing this but I think it does what you want.
假设:数据是一个数组,每个数组元素都是一个对象(哈希).仅在Windows上的Chrome中进行了测试.
Assumptions: Data is an array, with each array element being an object (hash). Tested in Chrome on Windows only.
<html>
<head>
<script src="http://code.jquery.com/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function read_record(data) {
$.each(data, function(key,value) {
if ($.isPlainObject(value))
read_record(value);
else
$('#details').append('<li>' + key + ' = ' + value + '</li>');
});
}
$(document).ready(function() {
var data = [
{
"Name" : "John",
"Company" : "Doe",
"Address" : {
"Street" : "123 Main Street",
"City" : "San Francisco"
}
},
{
"Name" : "Jane",
"Company" : "Johnson",
"Address" : {
"Street" : "57 Heinz Lane",
"City" : "Dallas"
}
}
];
read_record(data);
});
</script>
</head>
<body>
<ul id="details"></ul>
</body>
</html>
产生:
- 姓名=约翰
- 公司=能源部
- 街道=大街123号
- 城市=旧金山
- 姓名=简
- 公司=约翰逊
- 街道=亨氏巷57号
- 城市=达拉斯
这篇关于遍历和打印嵌套的JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文