Created
April 24, 2020 17:37
-
-
Save gaplo917/573cb13d9022893f3c6022e97081ddd6 to your computer and use it in GitHub Desktop.
Quick Node Script to flatten JSON
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
// https://stackoverflow.com/questions/19098797/fastest-way-to-flatten-un-flatten-nested-json-objects | |
function flatten(data) { | |
const result = {} | |
function recurse(cur, prop) { | |
if (Object(cur) !== cur) { | |
result[prop] = cur | |
} else if (Array.isArray(cur)) { | |
for (let i = 0, l = cur.length; i < l; i++) | |
recurse(cur[i], prop + '[' + i + ']') | |
if (l === 0) | |
result[prop] = [] | |
} else { | |
let isEmpty = true | |
for (let p in cur) { | |
isEmpty = false | |
recurse(cur[p], prop ? prop + '.' + p : p) | |
} | |
if (isEmpty && prop) | |
result[prop] = {} | |
} | |
} | |
recurse(data, '') | |
return result | |
} | |
const fs = require('fs') | |
const tw = String(fs.readFileSync('./target.json')) | |
const twJsObj = JSON.parse(tw) | |
const twFlattenJson = JSON.stringify(flatten(twJsObj)) | |
fs.writeFileSync('./flatten.json', twFlattenJson) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment