json10
Version:
Handle circural references, comments and many more inside JSON
56 lines • 2.38 kB
JavaScript
import { ___NS__cloneDeep, ___NS__get, ___NS__isArray, ___NS__isFunction, ___NS__isObject, ___NS__isUndefined, ___NS__merge, ___NS__set } from 'tnp-core/lib-prod';
import { walk } from 'lodash-walk-object/lib-prod';
import { CLASS } from 'typescript-class-helpers/lib-prod';
// import { Log } from 'ng2-logger'
// const log = Log.create('JSON10')
// let counter = 0
export class JSON10 {
static structureArray(anyJSON, options) {
let pathes = [];
const { include, exclude } = options || {};
walk.Object(anyJSON, (value, lodashPath) => {
if (!___NS__isUndefined(value)) {
pathes.push(lodashPath);
}
}, { include, exclude, checkCircural: true });
return pathes;
}
static cleaned(json, onCircs, options) {
// console.log('BETTER SRUGUB', json)
const result = ___NS__isArray(json) ? [] : {};
const classFN = CLASS.OBJECT(json).isClassObject && CLASS.getFromObject(json);
const { exclude, include, breadthWalk } = options || { exclude: [], include: [], breadthWalk: false };
const { circs } = walk.Object(json, (value, lodashPath, changeValueTo, options) => {
if (___NS__isObject(value) && options.isCircural) {
___NS__set(result, lodashPath, null);
}
else {
___NS__set(result, lodashPath, ___NS__cloneDeep(value));
}
}, { include, exclude, breadthWalk, checkCircural: true });
if (___NS__isFunction(onCircs)) {
onCircs(circs);
}
return ___NS__isFunction(classFN) ? ___NS__merge(new classFN(), result) : result;
}
static stringify(anyJSON, replace, spaces, onCircs) {
const json = this.cleaned(anyJSON, onCircs);
return JSON.stringify(json, replace, spaces);
}
static parse(json, circs = []) {
let res = JSON.parse(json);
if (___NS__isArray(circs)) {
circs.forEach(({ circuralTargetPath, pathToObj }) => {
if (circuralTargetPath === '') {
___NS__set(res, pathToObj, res);
}
else {
let v = ___NS__get(res, circuralTargetPath);
___NS__set(res, pathToObj, v);
}
});
}
return res;
}
}
//# sourceMappingURL=index.js.map