Skip to content

Instantly share code, notes, and snippets.

@elisherer
Created August 13, 2020 10:47
Show Gist options
  • Save elisherer/d0208db94cebf028e633eb77d6298167 to your computer and use it in GitHub Desktop.
Save elisherer/d0208db94cebf028e633eb77d6298167 to your computer and use it in GitHub Desktop.
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