Article Logo Go Back

Pretty Printing Javascript Object Literals

AvatarMay 1, 20195 minsTim Ellenberger

I recently published a very config-heavy graphics library for React, react-particles-webgl, and as I was building the demo page (go play with it!)I began realizing how convenient it would be to copy + paste the current config directly into your own code. I already had the entire particle config saved in React state for updating the particles as you change it's parameters. Luckily, all I needed was to get that object into the browser somehow.

Consulting the JSON.stringify() documentation shows that while it's possible to neatly indent an object as JSON, we cannot modify the formatting to make our JSON appear as a JavaScript object.

After pouring over countless Stack Overflow and Google search results, I finally came across a package for solving this exact problem: stringify-object.

Usage is just as simple as JSON.stringify().

dataconfig.jsjs
1import stringifyObject from 'stringify-object';23const config = {4  showCube: true,5  dimension: '3D',6  velocity: 2,7  boundaryType: 'bounce',8  antialias: true,9  particles: {10    colorMode: 'rainbow',11    color: '#3FB568',12    transparency: 0.9,13    shape: 'square',14    boundingBox: 'canvas',15    count: 500,16    minSize: 10,17    maxSize: 75,18    visible: true19  }20}2122const configString = stringifyObject(config, {23  indent: '  ',24  singleQuotes: true25});

After generating this string via stringifyObject(), one could simply run it through a syntax highlighter like I've detailed in my post building-react-code-blocks-with-prism to represent any object in the browser as it would appear in your code editor.


Need a developer? Drop me a line!

Bug?
Edit Post