Created
May 26, 2020 20:07
-
-
Save cdaringe/70166563e7c4c317e96da9638f7347fe to your computer and use it in GitHub Desktop.
json-compactor.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as fs from 'fs' | |
function isPrimitive (v: any) { | |
const tOfV = typeof v | |
if (tOfV === 'object') return false | |
if (v === null || tOfV === 'boolean' || tOfV === 'bigint' || tOfV === 'number' || tOfV === 'string' || tOfV === 'undefined') { | |
return true | |
} | |
return false | |
} | |
function walk (obj: any, acc: string[] = [], fields: string[] = []) { | |
for (const k in obj) { | |
const nextFields = [...fields, k] | |
const v = obj[k] | |
if (isPrimitive(v)) { | |
acc.push(`${nextFields.join('.')}: ${typeof v}`) | |
} else { | |
if (Array.isArray(v) && v.length > 0) { | |
walk(v[0], acc, nextFields) | |
} else { | |
walk(v, acc, nextFields) | |
} | |
} | |
} | |
} | |
const json = JSON.parse(fs.readFileSync('./best.file.json').toString()) | |
const acc: string[] = [] | |
const fields: string[] = [] | |
walk(json, acc, fields) | |
console.log(acc.join('\n')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment