UNPKG

json10

Version:

Handle circural references, comments and many more inside JSON

64 lines (60 loc) 2.25 kB
import { _ } from 'tnp-core/browser'; import { walk } from 'lodash-walk-object/browser'; import { CLASS } from 'typescript-class-helpers/browser'; // import { Log } from 'ng2-logger' // const log = Log.create('JSON10') // let counter = 0 class JSON10 { static structureArray(anyJSON, options) { let pathes = []; const { include, exclude } = options || {}; walk.Object(anyJSON, (value, lodashPath) => { if (!_.isUndefined(value)) { pathes.push(lodashPath); } }, { include, exclude, checkCircural: true }); return pathes; } static cleaned(json, onCircs, options) { // console.log('BETTER SRUGUB', json) const result = _.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 (_.isObject(value) && options.isCircural) { _.set(result, lodashPath, null); } else { _.set(result, lodashPath, _.cloneDeep(value)); } }, { include, exclude, breadthWalk, checkCircural: true }); if (_.isFunction(onCircs)) { onCircs(circs); } return _.isFunction(classFN) ? _.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 (_.isArray(circs)) { circs.forEach(({ circuralTargetPath, pathToObj }) => { if (circuralTargetPath === '') { _.set(res, pathToObj, res); } else { let v = _.get(res, circuralTargetPath); _.set(res, pathToObj, v); } }); } return res; } } /** * Generated bundle index. Do not edit. */ export { JSON10 }; //# sourceMappingURL=json10.mjs.map