UNPKG

flatted

Version:

A super light and fast circular JSON parser.

2 lines (1 loc) • 1.34 kB
const{parse:t,stringify:e}=JSON,{keys:n}=Object,r=String,o="string",s={},l="object",c=(t,e)=>e,f=t=>{if(typeof t===l&&t)for(let e=n(t),{length:s}=e,l=0;l<s;l++){const n=e[l];typeof t[n]===o&&(t[n]=new r(t[n]))}return t},i=(t,e,n)=>{const o=r(e.push(n)-1);return t.set(n,o),o},a=(e,o)=>{const i=t(e).map(f),a=o||c;let u=i[0];if(typeof u===l&&u){const t=[],e=((t,e,o,c)=>f=>{for(let i=n(f),{length:a}=i,u=0;u<a;u++){const n=i[u],a=f[n];if(a instanceof r){const r=t[+a];typeof r===l&&r&&!o.has(r)?(o.add(r),f[n]=s,e.push({o:f,k:n,r:r})):f[n]=c.call(f,n,r)}else f[n]!==s&&(f[n]=c.call(f,n,a))}return f})(i,t,new Set,a);u=e(u);let o=0;for(;o<t.length;)e(t[o++].r);for(;o--;){const{o:e,k:n,r:r}=t[o];e[n]=a.call(e,n,r)}}return a.call({"":u},"",u)},u=(t,n,s)=>{const f=Array.isArray(n)?[]:null;if(f)for(let t=0;t<n.length;t++){const e=n[t];typeof e!==o&&"number"!=typeof e||f.push(r(e))}const a={"":t},u=f?function(t,e){return this===a||Array.isArray(this)||-1<f.indexOf(t)?e:void 0}:n||c,p=new Map,h=[],y=[];let g=+i(p,h,u.call(a,"",t)),d=!g;for(;g<h.length;)d=!0,y[g]=e(h[g++],w,s);return"["+y.join(",")+"]";function w(t,e){if(d)return d=!d,e;const n=u.call(this,t,e);switch(typeof n){case l:if(null===n)return n;case o:return p.get(n)||i(p,h,n)}return n}},p=e=>t(u(e)),h=t=>a(e(t));export{h as fromJSON,a as parse,u as stringify,p as toJSON};