Skip to content

Instantly share code, notes, and snippets.

@nrkn
Last active July 19, 2023 08:24
Show Gist options
  • Select an option

  • Save nrkn/c7a89bb7039182314415 to your computer and use it in GitHub Desktop.

Select an option

Save nrkn/c7a89bb7039182314415 to your computer and use it in GitHub Desktop.
Human readable json stringify where simple arrays use only one line
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