Created
August 13, 2020 10:47
-
-
Save elisherer/d0208db94cebf028e633eb77d6298167 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
const obj = { | |
"first_name": "John", | |
"last_name": "Smith", | |
"age": 21, | |
"hobbies": [ "programming", "workout", null, undefined, 24, "\"has double quotes\"" ], | |
"nested": { | |
"arr": [ "one", "two", "three" ], | |
}, | |
"nested_arr": [ | |
"first as string", | |
{ | |
"latin": [ "alpha", "beta", "[gamma]" ] | |
}, | |
null | |
] | |
}; | |
const stringify = (obj, indent = 2) => | |
JSON.stringify(obj, (key, value) => { | |
if (Array.isArray(value) && !value.some(x => x && typeof x === 'object')) { | |
return `\uE000${JSON.stringify(value.map(v => typeof v === 'string' ? v.replace(/"/g, '\uE001') : v))}\uE000`; | |
} | |
return value; | |
}, indent).replace(/"\uE000([^\uE000]+)\uE000"/g, match => match.substr(2, match.length - 4).replace(/\\"/g, '"').replace(/\uE001/g, '\\\"')); | |
console.log(stringify(obj)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment