Last active
October 11, 2022 22:19
-
-
Save zachvictor/4e05cc97e857186203e3a706d78a3494 to your computer and use it in GitHub Desktop.
JSON stringify function that compacts numeric arrays, putting brackets and values on the same line
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
function compactify(ugly) { | |
// Step 1: JSON stringify with indentation (4 spaces) | |
const first_pass = JSON.stringify(JSON.parse(ugly), null, 4) | |
// Step 2: Put comma-sep. numbers on same line | |
const comma_num_newline_ptn = /,\n +((\d\.)?\d+)/g | |
const num_same_line = first_pass.replace(comma_num_newline_ptn, ', $1') | |
// Step 3: Put flat arrays on same line | |
const flat_array_ptn = /\[\n\s+(([\d.]+, )+[\d.]+)\n\s+\]/g | |
return num_same_line.replace(flat_array_ptn, '[$1]') | |
} | |
/* | |
Before: | |
var ugly = `{"uuid": "5414681d-1b0c-439c-8d09-ca7c7a94e67e", "things": [{"ts": 1662050506431, "vectors": [[0.299479, 0.255556, 0.2, 0.075, 0.102], [0.511979, 0.081944, 0.051, 0.086, 0.129], [0.428125, 0.478241, 0.376, 0.369, 0.369]], "pick": [0, 1, 2]}, {"ts": 1662050569527, "vectors": [[0.511458, 0.080556, 0.051, 0.082, 0.133], [0.303646, 0.250926, 0.224, 0.094, 0.114], [0.509896, 0.352315, 0.384, 0.188, 0.22]], "pick": [1, 0, 2]}, {"ts": 1662050570559, "vectors": [[0.754167, 0.335185, 0.051, 0.086, 0.141], [0.519271, 0.065278, 0.161, 0.184, 0.247]], "pick": [2, 1]}]}` | |
After: | |
console.log(compactify(ugly)) | |
{ | |
"uuid": "5414681d-1b0c-439c-8d09-ca7c7a94e67e", | |
"things": [ | |
{ | |
"ts": 1662050506431, | |
"vectors": [ | |
[0.299479, 0.255556, 0.2, 0.075, 0.102], | |
[0.511979, 0.081944, 0.051, 0.086, 0.129], | |
[0.428125, 0.478241, 0.376, 0.369, 0.369] | |
], | |
"pick": [0, 1, 2] | |
}, | |
{ | |
"ts": 1662050569527, | |
"vectors": [ | |
[0.511458, 0.080556, 0.051, 0.082, 0.133], | |
[0.303646, 0.250926, 0.224, 0.094, 0.114], | |
[0.509896, 0.352315, 0.384, 0.188, 0.22] | |
], | |
"pick": [1, 0, 2] | |
}, | |
{ | |
"ts": 1662050570559, | |
"vectors": [ | |
[0.754167, 0.335185, 0.051, 0.086, 0.141], | |
[0.519271, 0.065278, 0.161, 0.184, 0.247] | |
], | |
"pick": [2, 1] | |
} | |
] | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment