Skip to content

Instantly share code, notes, and snippets.

@cdaringe
Created May 26, 2020 20:07
Show Gist options
  • Select an option

  • Save cdaringe/70166563e7c4c317e96da9638f7347fe to your computer and use it in GitHub Desktop.

Select an option

Save cdaringe/70166563e7c4c317e96da9638f7347fe to your computer and use it in GitHub Desktop.

Revisions

  1. cdaringe created this gist May 26, 2020.
    32 changes: 32 additions & 0 deletions json-compactor.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,32 @@
    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'))