jFormat 将json 字符串或对象,转换为格式字符串(含缩进符号)。
支持cmd、amd、commonjs
/**
* 格式化输出 json
* created by zcyue at 2019-01-25
*/
; (function (global, factory) {
"use strict";
if (typeof module === "object" && typeof module.exports === "object") {
// For CommonJS and CommonJS-like environments where a proper `window`
// is present, execute the factory and get jFormat.
// For environments that do not have a `window` with a `document`
// (such as Node.js), expose a factory as module.exports.
// This accentuates the need for the creation of a real `window`.
// See ticket #14549 for more info.
module.exports = global.document ?
factory(global, true) :
function (w) {
if (!w.document) {
throw new Error("jFormat requires a window with a document");
}
return factory(w);
};
} else {
try{
if(define && define.cmd) {
define(function () {
return factory(global);
});
}
}catch(e){
factory(global);
}
}
})(typeof window !== "undefined" ? window : this, function (window, noGlobal) {
'use strict'
const NEW_LINE = '\n';
const TAB = '\t';
const EXPAND = '+';
const UN_EXPAND = '-';
/**
* 判断是否为数组
* @param {*} it
*/
function isArray(it) {
return Object.prototype.toString.call(it) === '[object Array]';
}
/**
* 判断是否为对象
* @param {*} it
*/
function isObject(it) {
return Object.prototype.toString.call(it) === '[object Object]';
}
function trimL(str) {
let pattern = /^\s*(\S)/g;
if (typeof str !== 'string') str = str + ''
return str.replace(pattern, '$1');
}
function tab(count) {
return TAB.repeat(count);
}
function formatArray(arr, level) {
level = level || 0;
if (arr.length <= 0) return `${UN_EXPAND}[${NEW_LINE}${tab(level)}]`;
let str = '';
Array.prototype.forEach.call(arr, v => {
let s;
if (isArray(v)) {
s = formatArray(v, level + 1);
} else if (isObject(v)) {
s = formatObject(v, level + 1);
} else {
s = tab(level + 1) + '"' + v + '"';
}
if (str) str += ',' + NEW_LINE;
str += s;
});
return tab(level) + `${UN_EXPAND}[${NEW_LINE}` + str + `${NEW_LINE}${tab(level)}]`;
}
function formatObject(obj, level) {
level = level || 0;
let str = '';
Array.prototype.forEach.call(Object.keys(obj), key => {
if (obj.hasOwnProperty(key)) {
let v = obj[key];
let s;
if (isArray(v)) {
s = formatArray(v, level + 1);
} else if (isObject(v)) {
s = formatObject(v, level + 1);
} else {
s = '"' + v + '"';
}
if (str) str += ',';
str += NEW_LINE + tab(level + 1) + '"' + key + '"' + ': ' + trimL(s);
}
});
return tab(level) + UN_EXPAND + '{' + str + NEW_LINE + tab(level) + '}';
}
/**
* json 字符串格式化
* @param {*} str
*/
function formatJSON(str) {
let obj = typeof str === 'string' ? JSON.parse(str) : str
return isArray(obj) ? formatArray(obj) : formatObject(obj);
}
// 是代码支持 amd 模块加载
if (typeof define === "function" && define.amd) {
define("jFormat", [], function () {
return formatJSON;
});
}
window.jFormat = formatJSON;
return formatJSON;
})
示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="jFormat.js"></script>
</head>
<body>
<script>
var obj = {"a":{"aa":13},"b":[{"bb":"bbValue"},{"bb2":"bb2v","bc2":19}],"c":{"name":"JAY","age":43}};
console.log(jFormat(obj));
</script>
</body>
</html>
控制台输出:
至此,结束。