Skip to content

Instantly share code, notes, and snippets.

@cdaringe
Created May 26, 2020 20:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cdaringe/70166563e7c4c317e96da9638f7347fe to your computer and use it in GitHub Desktop.
Save cdaringe/70166563e7c4c317e96da9638f7347fe to your computer and use it in GitHub Desktop.
json-compactor.ts
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