Skip to content

Instantly share code, notes, and snippets.

@songz
Last active November 2, 2017 01:44
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 songz/2c921ea7b8d4ed437ca701dd3cac059c to your computer and use it in GitHub Desktop.
Save songz/2c921ea7b8d4ed437ca701dd3cac059c to your computer and use it in GitHub Desktop.
// Works on simple data structures, did not test on more complex cases
// defined here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
const stringify = (jsobj) => {
const typ = typeof(jsobj);
if(typ==='string') return `"${jsobj}"`;
if(typ==='number' || typ==='boolean') return `${jsobj}`;
let [start, result, ending] = ['', '', ''];
if(jsobj.length === undefined) {
start = "{";
result = Object.keys(jsobj).reduce((acc, k) => `${acc}"${k}":${stringify(jsobj[k])},`, '');
ending = "}";
} else {
start = "[";
result = jsobj.reduce( (acc, e) => `${acc}${stringify(e)},`, '');
ending = "]";
}
return `${start}${result.slice(0,-1)}${ending}`; // slice removes last comma
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment