UNPKG

typescript-util

Version:

JS/TS 的简单工具

63 lines 1.51 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.JsonTool = void 0; /** * JsonTool * @author 冰凝 * @date 2022-09-19 09:42:20 **/ class JsonTool { static toJson(o) { return JSON.stringify(o); } static toNiceJson(o) { return JSON.stringify(o, null, 4); } /** * @param s {string} * @return boolean */ static isJsonArray(s) { return s && s.startsWith('[') && s.endsWith(']'); } /** * @param s {string} * @return boolean */ static isJsonObject(s) { return s && s.startsWith('{') && s.endsWith('}'); } /** * @param s {string} * @param isArr {(arr: Array<any>) => any} * @param isObj {(obj: Record<string, any>) => any} * @param other {(v: null | undefined | number | string) => any} */ static switchParse(s, isArr, isObj, other = () => { }) { if (!s) { return null; } if (this.isJsonArray(s)) { return isArr(JSON.parse(s)); } if (this.isJsonObject(s)) { return isObj(JSON.parse(s)); } // @ts-ignore return other(s); } static parse(json) { if (!json) { return json; } try { return JSON.parse(json); } catch (e) { console.debug('JSON 解析错误: ', e); } return null; } } exports.JsonTool = JsonTool; //# sourceMappingURL=JsonTool.js.map