Browse Source

JSON格式化支持BigNumber

zxlie 7 years ago
parent
commit
dbd05da257

+ 17 - 12
apps/json-format/automatic.js

@@ -2,6 +2,11 @@
  * Json Page Automatic Format Via FeHelper
  * @author zhaoxianlie
  */
+
+
+// json with bigint supported
+Tarp.require('../static/vendor/json-bigint/index');
+
 module.exports = (() => {
 
     "use strict";
@@ -102,14 +107,13 @@ module.exports = (() => {
 
         // JSONP形式下的callback name
         let funcName = null;
-        // json对象
         let jsonObj = null;
-        let newSource = source;
         let fnTry = null;
         let fnCatch = null;
 
         // 下面校验给定字符串是否为一个合法的json
         try {
+
             // 再看看是不是jsonp的格式
             let reg = /^([\w\.]+)\(\s*([\s\S]*)\s*\)$/gm;
             let reTry = /^(try\s*\{\s*)?/g;
@@ -127,8 +131,7 @@ module.exports = (() => {
             let matches = reg.exec(sourceReplaced);
             if (matches != null && (fnTry && fnCatch || !fnTry && !fnCatch)) {
                 funcName = matches[1];
-                newSource = matches[2];
-                jsonObj = new Function("return " + newSource)();
+                source = matches[2];
             } else {
                 reg = /^([\{\[])/;
                 if (!reg.test(source)) {
@@ -136,18 +139,20 @@ module.exports = (() => {
                 }
             }
 
-            // 强化验证
-            if (jsonObj == null || typeof jsonObj !== 'object') {
+            // 这里可能会throw exception
+            jsonObj = JSON.parse(source);
+        } catch (ex) {
+            // new Function的方式,能自动给key补全双引号,但是不支持bigint,所以是下下策,放在try-catch里搞
+            try {
                 jsonObj = new Function("return " + source)();
-
                 // 还要防止下面这种情况:  "{\"ret\":\"0\", \"msg\":\"ok\"}"
                 if (typeof jsonObj === "string") {
                     // 再来一次
                     jsonObj = new Function("return " + jsonObj)();
                 }
+            } catch (exx) {
+                return;
             }
-        } catch (ex) {
-            return;
         }
 
         // 是json格式,可以进行JSON自动格式化
@@ -158,13 +163,13 @@ module.exports = (() => {
                 // 如果newSource的长度比原source长度短很多的话,猜测应该是格式化错了,需要撤销操作
                 // 这里一定要unicode decode一下,要不然会出现误判
                 let len1 = jsonStr.replace(/'|"|\s/g, '').length;
-                let len2 = (_uniDecode(newSource)).replace(/'|"|\s/g, '').length;
+                let len2 = (_uniDecode(source)).replace(/'|"|\s/g, '').length;
                 // 误差不允许超过20%
                 if (Math.abs(len1 - len2) / ((len1 + len2) / 2) > 0.2) {
                     return;
                 }
 
-                newSource = jsonStr;
+                source = jsonStr;
             } catch (ex) {
                 // 通过JSON反解不出来的,一定有问题
                 return;
@@ -174,7 +179,7 @@ module.exports = (() => {
             _loadCss();
 
             // 格式化
-            Tarp.require('../json-format/format-lib').format(newSource);
+            Tarp.require('../json-format/format-lib').format(source);
 
             // 如果是JSONP格式的,需要把方法名也显示出来
             if (funcName != null) {

+ 17 - 12
apps/json-format/format-lib.js

@@ -314,7 +314,7 @@ var JsonFormatEntrance = (function () {
         // 事件绑定
         _addEvents();
         // 支持文件下载
-        _downloadSupport(JSON.parse(jsonStr));
+        _downloadSupport(JSON.stringify(JSON.parse(jsonStr), null, 4));
     };
 
     var _loadJs = function () {
@@ -327,15 +327,14 @@ var JsonFormatEntrance = (function () {
 
     /**
      * 直接下载,能解决中文乱码
-     * @param json
+     * @param content
      * @private
      */
-    var _downloadSupport = function (json) {
+    var _downloadSupport = function (content) {
 
         // 下载链接
         var localUrl = location.href;
         var dt = (new Date()).format('yyyyMMddHHmmss');
-        var content = JSON.stringify(json, null, 4);
         content = ['/* ', localUrl, ' */', '\n', content].join('');
         var blob = new Blob([content], {type: 'application/octet-stream'});
 
@@ -701,15 +700,21 @@ var JsonFormatDealer = (function () {
 
         // Add an 'expander' first (if this is object/array with non-zero size)
         if (type === TYPE_OBJECT || type === TYPE_ARRAY) {
-            nonZeroSize = false;
-            for (objKey in value) {
-                if (value.hasOwnProperty(objKey)) {
-                    nonZeroSize = true;
-                    break; // no need to keep counting; only need one
+
+            if (typeof JSON.BigNumber === 'function' && value instanceof JSON.BigNumber) {
+                value = JSON.stringify(value);
+                type = TYPE_NUMBER;
+            } else {
+                nonZeroSize = false;
+                for (objKey in value) {
+                    if (value.hasOwnProperty(objKey)) {
+                        nonZeroSize = true;
+                        break; // no need to keep counting; only need one
+                    }
                 }
+                if (nonZeroSize)
+                    kvov.appendChild(templates.t_exp.cloneNode(false));
             }
-            if (nonZeroSize)
-                kvov.appendChild(templates.t_exp.cloneNode(false));
         }
 
         // If there's a key, add that before the value
@@ -876,7 +881,7 @@ var JsonFormatDealer = (function () {
             var obj,
                 text = msg.text;
             try {
-                obj = new Function('return ' + text)();
+                obj = JSON.parse(text);
             }
             catch (e) {
                 // Not JSON; could be JSONP though.

+ 14 - 92
apps/json-format/index.js

@@ -4,6 +4,9 @@
 let editor = {};
 let LOCAL_KEY_OF_LAYOUT = 'local-layout-key';
 
+// json with bigint supported
+Tarp.require('../static/vendor/json-bigint/index');
+
 new Vue({
     el: '#pageContainer',
     data: {
@@ -82,21 +85,22 @@ new Vue({
                 let matches = reg.exec(source);
                 if (matches != null) {
                     funcName = matches[1];
-                    let newSource = matches[2];
-                    jsonObj = new Function("return " + newSource)();
+                    source = matches[2];
                 }
-
-                if (jsonObj == null || typeof jsonObj !== 'object') {
+                // 这里可能会throw exception
+                jsonObj = JSON.parse(source);
+            } catch (ex) {
+                // new Function的方式,能自动给key补全双引号,但是不支持bigint,所以是下下策,放在try-catch里搞
+                try {
                     jsonObj = new Function("return " + source)();
-
                     // 还要防止下面这种情况:  "{\"ret\":\"0\", \"msg\":\"ok\"}"
                     if (typeof jsonObj === "string") {
                         // 再来一次
                         jsonObj = new Function("return " + jsonObj)();
                     }
+                } catch (exx) {
+                    this.errorMsg = ex.message;
                 }
-            } catch (ex) {
-                this.errorMsg = ex.message;
             }
 
             // 是json格式,可以进行JSON自动格式化
@@ -154,7 +158,7 @@ new Vue({
                 this.$refs.btnLeftRight.classList.add('selected');
                 this.$refs.btnUpDown.classList.remove('selected');
             }
-            localStorage.setItem(LOCAL_KEY_OF_LAYOUT,type);
+            localStorage.setItem(LOCAL_KEY_OF_LAYOUT, type);
         },
 
         lintOn: function () {
@@ -196,90 +200,8 @@ new Vue({
         },
 
         setDemo: function () {
-            let demo = {
-                date: "20180322",
-                message: "Success !",
-                status: 200,
-                city: "北京",
-                count: 632,
-                data: {
-                    shidu: "34%",
-                    pm25: 73,
-                    pm10: 91,
-                    quality: "良",
-                    wendu: "5",
-                    ganmao: "极少数敏感人群应减少户外活动",
-                    yesterday: {
-                        date: "21日星期三",
-                        sunrise: "06:19",
-                        high: "高温 11.0℃",
-                        low: "低温 1.0℃",
-                        sunset: "18:26",
-                        aqi: 85,
-                        fx: "南风",
-                        fl: "<3级",
-                        type: "多云",
-                        notice: "阴晴之间,谨防紫外线侵扰"
-                    },
-                    forecast: [{
-                        date: "22日星期四",
-                        sunrise: "06:17",
-                        high: "高温 17.0℃",
-                        low: "低温 1.0℃",
-                        sunset: "18:27",
-                        aqi: 98,
-                        fx: "西南风",
-                        fl: "<3级",
-                        type: "晴",
-                        notice: "愿你拥有比阳光明媚的心情"
-                    }, {
-                        date: "23日星期五",
-                        sunrise: "06:16",
-                        high: "高温 18.0℃",
-                        low: "低温 5.0℃",
-                        sunset: "18:28",
-                        aqi: 118,
-                        fx: "无持续风向",
-                        fl: "<3级",
-                        type: "多云",
-                        notice: "阴晴之间,谨防紫外线侵扰"
-                    }, {
-                        date: "24日星期六",
-                        sunrise: "06:14",
-                        high: "高温 21.0℃",
-                        low: "低温 7.0℃",
-                        sunset: "18:29",
-                        aqi: 52,
-                        fx: "西南风",
-                        fl: "<3级",
-                        type: "晴",
-                        notice: "愿你拥有比阳光明媚的心情"
-                    }, {
-                        date: "25日星期日",
-                        sunrise: "06:13",
-                        high: "高温 22.0℃",
-                        low: "低温 7.0℃",
-                        sunset: "18:30",
-                        aqi: 71,
-                        fx: "西南风",
-                        fl: "<3级",
-                        type: "晴",
-                        notice: "愿你拥有比阳光明媚的心情"
-                    }, {
-                        date: "26日星期一",
-                        sunrise: "06:11",
-                        high: "高温 21.0℃",
-                        low: "低温 8.0℃",
-                        sunset: "18:31",
-                        aqi: 97,
-                        fx: "西南风",
-                        fl: "<3级",
-                        type: "多云",
-                        notice: "阴晴之间,谨防紫外线侵扰"
-                    }]
-                }
-            };
-            editor.setValue(JSON.stringify(demo));
+            let demo = '{"BigIntSupported":995815895020119788889,"date":"20180322","message":"Success !","status":200,"city":"北京","count":632,"data":{"shidu":"34%","pm25":73,"pm10":91,"quality":"良","wendu":"5","ganmao":"极少数敏感人群应减少户外活动","yesterday":{"date":"21日星期三","sunrise":"06:19","high":"高温 11.0℃","low":"低温 1.0℃","sunset":"18:26","aqi":85,"fx":"南风","fl":"<3级","type":"多云","notice":"阴晴之间,谨防紫外线侵扰"},"forecast":[{"date":"22日星期四","sunrise":"06:17","high":"高温 17.0℃","low":"低温 1.0℃","sunset":"18:27","aqi":98,"fx":"西南风","fl":"<3级","type":"晴","notice":"愿你拥有比阳光明媚的心情"},{"date":"23日星期五","sunrise":"06:16","high":"高温 18.0℃","low":"低温 5.0℃","sunset":"18:28","aqi":118,"fx":"无持续风向","fl":"<3级","type":"多云","notice":"阴晴之间,谨防紫外线侵扰"},{"date":"24日星期六","sunrise":"06:14","high":"高温 21.0℃","low":"低温 7.0℃","sunset":"18:29","aqi":52,"fx":"西南风","fl":"<3级","type":"晴","notice":"愿你拥有比阳光明媚的心情"},{"date":"25日星期日","sunrise":"06:13","high":"高温 22.0℃","low":"低温 7.0℃","sunset":"18:30","aqi":71,"fx":"西南风","fl":"<3级","type":"晴","notice":"愿你拥有比阳光明媚的心情"},{"date":"26日星期一","sunrise":"06:11","high":"高温 21.0℃","low":"低温 8.0℃","sunset":"18:31","aqi":97,"fx":"西南风","fl":"<3级","type":"多云","notice":"阴晴之间,谨防紫外线侵扰"}]}}';
+            editor.setValue(demo);
         }
     }
 });

+ 3 - 2
apps/manifest.json

@@ -1,6 +1,6 @@
 {
   "name": "WEB前端助手(FeHelper)",
-  "version": "2018.05.2117",
+  "version": "2018.05.2212",
   "manifest_version": 2,
   "default_locale": "zh_CN",
   "description": "FE助手:包括JSON格式化、二维码生成与解码、信息编解码、代码压缩、美化、页面取色、Markdown与HTML互转、网页转为图片、正则表达式、时间转换工具、编码规范检测、页面性能检测、Ajax接口调试",
@@ -71,7 +71,8 @@
     "static/vendor/syntaxhighlighter/shCore.js",
     "static/vendor/syntaxhighlighter/shBrushJScript.js",
     "static/vendor/syntaxhighlighter/shBrushCss.js",
-    "static/css/syntax-highlighter.css"
+    "static/css/syntax-highlighter.css",
+    "static/vendor/json-bigint/index.js"
   ],
   "content_scripts": [
     {

File diff suppressed because it is too large
+ 0 - 0
apps/static/vendor/json-bigint/index.js


Some files were not shown because too many files changed in this diff