有很多时候我们需要展示json数据,并不仅仅是数据展示,如让json中的数据像树形一样展示实现可折叠,废话不多说直接上步骤:
1.项目中引入外部插件(可以百度或者加入下方交流群,群里有你想要的!)
jquery.json-viewer.js
jquery.json-viewer.js
2.页面的写法
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery查看json格式数据插件</title>
<link rel="stylesheet" type="text/css" href="http://www.jq22.com/jquery/bootstrap-3.3.4.css">
<link href="css/jquery.json-viewer.css" type="text/css" rel="stylesheet" />
<style>
body{background-color: #F7F7F7}
</style>
</head>
<body>
<div class="jq22-container">
<div class="container" style="margin-top: 1em;">
<div class="row">
<textarea class="form-control" id="json-input" rows="15" >
{
"id": 1001,
"type": "donut",
"name": "Cake",
"description": "http://www.jq22.com",
"price": 2.55,
"available": {
store: 42,
warehouse: 600
},
"topping": [
{ "id": 5001, "type": "None" },
{ "id": 5002, "type": "Glazed" },
{ "id": 5005, "type": "Sugar" },
{ "id": 5003, "type": "Chocolate" },
{ "id": 5004, "type": "Maple" }
]
}
</textarea>
<pre id="json-renderer"></pre>
</div>
</div>
<script src="http://www.jq22.com/jquery/jquery-1.10.2.js"></script>
<script src="js/jquery.json-viewer.js"></script>
<script type="text/javascript">
$(function() {
try {
//获取该json数据
var input = eval('(' + $('#json-input').val() + ')');
}
catch (error) {
return alert("Cannot eval JSON: " + error);
}
//初始化json格式折叠展示
$('#json-renderer').jsonViewer(input);
});
</script>
</body>
</html>
3.最终页面显示效果如下:
向下箭头均可点击折叠该json数据,如有疑问请加群咨询!