Skip to content

Instantly share code, notes, and snippets.

@CezaryDanielNowak
Last active January 19, 2022 15:23
Show Gist options
  • Save CezaryDanielNowak/e36ad5e1c7a2d927fc07b52708806ed6 to your computer and use it in GitHub Desktop.
Save CezaryDanielNowak/e36ad5e1c7a2d927fc07b52708806ed6 to your computer and use it in GitHub Desktop.
/*
* I had to print a lot of json data on a printer so I wanted to make it
* as compact as possible.
*
* This snippet changes text JSON into compact form.
*
* input:
* `{
* "width": 1080,
* "height": 1920,
* "data": [
* "test"
* ]
* }`
*
* output:
* "width": 1080,
* "height": 1920
* "data": [
* "test"
*/
function compactJSON(textJSON) {
console.log('textJSON', textJSON);
const linesArray = `${textJSON}`
.replace(/\r/g, '') // get rid of windows-style newlines
.split('\n');
linesArray.forEach((value, i) => {
if (value.replace(/[\[\]{,}]/g, '').trim() === '')
linesArray[i] = ''; // remove lines with no meaning
});
return linesArray
.filter(Boolean) // remove empty lines
.join('\n');
}
// specific use for running code from web console and google spreadsheets
alert('now activate element you want to read');
setTimeout(() => {
navigator
.clipboard
.writeText(compactJSON(document.activeElement.innerText))
.then(() => { alert('copied to clipboard') })
.catch(() => {
alert('could not copy text; Copy from console by yourself.');
});
}, 2500);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment