jQuery格式化顯示json數據


一、概述

JSONView

在gitlab上面,有一個jQuery JSONView插件,地址為:https://github.com/yesmeck/jquery-jsonview

demo地址:http://yesmeck.github.io/jquery-jsonview/

 

注意:部分key前面有一個減號,點擊減號,就可以收縮了。點擊加號,可以展開。

但是這樣有一個問題,我需要用鼠標copy時,會帶有減號。復制之后,就是一個錯誤的數據!!!

 

jquery.json-viewer.js

下載地址為:http://www.jq22.com/jquery-info13551

demo地址:http://www.jq22.com/yanshi13551

注意:下載需要登錄jq22.com賬號

效果如下:

這個才是我們想要的效果,注意:它有豎條,可以方便查看層級關系。

而且copy數據時,也不會帶有多余的符號。點擊三角形符號,也可以方便收縮和展開!!

 

需求

有這樣一個需求,我用django開發一個接口,需要給其他人員展示數據。展示數據時,默認直接展開json 格式化好的數據,方便其他開發人員調用。

但是jq22.com 提供的插件,有一個textarea輸入框,我需要把它給去掉。

默認json格式化的數據中,key是沒有帶雙引號的,我需要默認勾選它,因此要修改js代碼。

 

二、修改插件代碼

基於上面的2點需求,下載jq22.com 提供的插件后,解壓代碼。

修改index.html,完整代碼如下:

<!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">
            <pre id="json-renderer"></pre>
        </div>
    </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 () {
        // json數據
        var json = {
            "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"}
            ]
        };

        //格式化json
        try {
            var input = eval('(' + JSON.stringify(json) + ')');
        } catch (error) {
            return alert("Cannot eval JSON: " + error);
        }
        var options = {
            //為Key添加雙引號
            withQuotes: true
        };
        $('#json-renderer').jsonViewer(input, options);
    });
</script>
</body>
</html>
View Code

 

直接用谷歌瀏覽器打開,效果如下:

 

三、嵌入到Django項目中

創建django項目

使用Pycharm創建一個Django項目,項目名為:json_view

 

 

創建靜態目錄

在項目根目錄創建 static 文件夾,在static 文件夾里面,創建 plugins 文件夾。

將上面修改好的插件,復制到此目錄。

index.html 復制到 templates 目錄下。

將index.html中的 http引用資源,下載到本地

wget http://www.jq22.com/jquery/bootstrap-3.3.4.css
wget http://www.jq22.com/jquery/jquery-1.10.2.js

放到對應的目錄中

 

此時,目錄結構如下:

./
├── application
│   ├── admin.py
│   ├── apps.py
│   ├── __init__.py
│   ├── migrations
│   │   └── __init__.py
│   ├── models.py
│   ├── tests.py
│   └── views.py
├── json_view_demo
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── manage.py
├── static
│   └── plugins
│       └── json-viewer
│           ├── css
│           │   ├── bootstrap-3.3.4.css
│           │   └── jquery.json-viewer.css
│           ├── index.html
│           ├── jquery
│           ├── js
│           │   ├── jquery-1.10.2.js
│           │   ├── jquery-1.11.0.min.js
│           │   └── jquery.json-viewer.js
│           └── www.jq22.com.txt
└── templates
    └── index.html

 

修改 json_view/settings.py,設置靜態目錄

STATIC_URL = '/static/'
STATICFILES_DIRS = (
    os.path.join(BASE_DIR,"static"),
)

 

修改  json_view/urls.py,增加路由

from django.contrib import admin
from django.urls import path
from application import views

urlpatterns = [
    path('admin/', admin.site.urls),
 path('', views.index),
    path('json/', views.json_data),
]

 

修改 application/view.py,增加視圖函數

from django.shortcuts import render,HttpResponse
import json

# Create your views here.
def index(request):
    return render(request, 'index.html')

def json_data(request):
    print(request.POST)
    data = {"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"}]}
    return HttpResponse(json.dumps(data))
View Code

 

修改 templates/index,調整靜態資源引用路徑,json改為ajax獲取。

<!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="/static/plugins/json-viewer/css/bootstrap-3.3.4.css">
    <link href="/static/plugins/json-viewer/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">
            <pre id="json-renderer"></pre>
        </div>
    </div>
</div>
{% csrf_token %}
<script src="/static/plugins/json-viewer/js/jquery-1.10.2.js"></script>
<script src="/static/plugins/json-viewer/js/jquery.json-viewer.js"></script>
<script type="text/javascript">
    $(function () {
        var csrf = $("[name=csrfmiddlewaretoken]").val();  //csrf
            $.ajax({  //發送ajax請求
                url: '/json/',
                type: 'POST',
                data: {
                    'csrfmiddlewaretoken': csrf,
                },
                success: function (data) {
                    try {
                        var input = eval('(' + data + ')');
                    } catch (error) {
                        return alert("Cannot eval JSON: " + error);
                    }
                    var options = {
                        //為Key添加雙引號
                        withQuotes: true
                    };
                    $('#json-renderer').jsonViewer(input, options);
                }
            });
    });
</script>
</body>
</html>
View Code

 

使用Pycharm啟動項目,訪問首頁:

http://127.0.0.1:8000/

 

效果如下:

 

另外我提供了一個demo,更換bootstrap版本,去除了多余的靜態文件。

github地址如下:

https://github.com/py3study/json_view_demo

 

有興趣的,可以下載使用。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM