Last active
July 19, 2023 08:24
-
-
Save nrkn/c7a89bb7039182314415 to your computer and use it in GitHub Desktop.
Human readable json stringify where simple arrays use only one 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
| const isPrimitive = obj => | |
| obj === null || | |
| [ 'string', 'number', 'boolean' ].includes( typeof obj ) | |
| const isArrayOfPrimitive = obj => | |
| Array.isArray( obj ) && obj.every( isPrimitive ) | |
| const format = arr => | |
| `^^^[ ${ | |
| arr.map( val => JSON.stringify( val ) ).join( ', ' ) | |
| } ]` | |
| const replacer = ( key, value ) => | |
| isArrayOfPrimitive( value ) ? format( value ) : value | |
| const expand = str => | |
| str.replace( | |
| /(?:"\^\^\^)(\[ .* \])(?:\")/g, ( match, a ) => | |
| a.replace( /\\"/g, '"' ) | |
| ) | |
| const stringify = obj => | |
| expand( JSON.stringify( obj, replacer, 2 ) ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment