jQuery格式化显示json数据

发布时间:2020-03-02 11:10:36编辑:admin阅读(2335)

    一、概述

    JSONView

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

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

    1.png

     

    注意:部分key前面有一个减号,点击减号,就可以收缩了。点击加号,可以展开。

    但是这样有一个问题,我需要用鼠标copy时,会带有减号。复制之后,就是一个错误的数据!!!

     

    jquery.json-viewer.js

    下载地址为:http://www.jq22.com/jquery-info13551

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

    注意:下载需要登录jq22.com账号

    效果如下:

    1.png

    这个才是我们想要的效果,注意:它有竖条,可以方便查看层级关系。

    而且copy数据时,也不会带有多余的符号。点击三角形符号,也可以方便收缩和展开!!

     

    需求

    有这样一个需求,我用django开发一个接口,需要给其他人员展示数据。展示数据时,默认直接展开json 格式化好的数据,方便其他开发人员调用。

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

    默认json格式化的数据中,key是没有带双引号的,我需要默认勾选它,因此要修改js代码。

     

    二、修改插件代码

    基于上面的2点需求,下载jq22.com 提供的插件后,解压代码。

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

    <!DOCTYPE html>
    <html>
    <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>
        <div style="margin-top: 1em;">
            <div>
                <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>

     

    直接用谷歌浏览器打开,效果如下:

    1.png

     

    三、嵌入到Django项目中

    创建django项目

    使用Pycharm创建一个Django项目,项目名为:json_view

     1.png

     

    创建静态目录

    在项目根目录创建 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))

     

    修改 templates/index,调整静态资源引用路径,json改为ajax获取。

    <!DOCTYPE html>
    <html>
    <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>
        <div style="margin-top: 1em;">
            <div>
                <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>

     

    使用Pycharm启动项目,访问首页:

    http://127.0.0.1:8000/

     

    效果如下:

    1.png

     

    另外我提供了一个demo,更换bootstrap版本,去除了多余的静态文件。

    github地址如下:

    https://github.com/py3study/json_view_demo


关键字