Skip to content

Instantly share code, notes, and snippets.

@JosePedroDias
Created September 29, 2019 14:37
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 JosePedroDias/81e696348f204a4fa11502369802b8a6 to your computer and use it in GitHub Desktop.
Save JosePedroDias/81e696348f204a4fa11502369802b8a6 to your computer and use it in GitHub Desktop.
jsonlish stringify

jsonlines and similar formats where each payload is stored as unindented JSON chunks divided by newlines are great for complex systems.

My application is more to aid in exploring large JSON files and copying/pasting, chunks in the editor, therefore made this small JSON stringifier that breaks the 1st level of arrays and objects with newlines,while returning valid JSON.

The placement of commas is intentional. This way one can find the item, right, shift+end, copy.

jsonlishStringify([4,true,'yay'])
`[
4
,true
,"yay"
]`

jsonlishStringify({a:4,b:true,c:'yay'])
`[
"a":4
,"b":true
,"c":"yay"
]`
function jsonlishStringify(data) {
if (data instanceof Array) {
return '[\n' + data.map((o) => JSON.stringify(o)).join('\n,') + '\n]';
}
if (typeof data === 'object') {
return (
'{\n' +
Object.entries(data)
.map(([k, v]) => {
return '"' + k + '":' + JSON.stringify(v);
})
.join('\n,') +
'\n}'
);
}
return JSON.stringify(data);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment