Skip to content Skip to sidebar Skip to footer

Pretty Printing Json With React

I'm using ReactJS and part of my app requires pretty printed JSON. I get some JSON like: { 'foo': 1, 'bar': 2 }, and if I run that through JSON.stringify(obj, null, 4) in the bro

Solution 1:

You'll need to either insert BR tag appropriately in the resulting string, or use for example a PRE tag so that the formatting of the stringify is retained:

var data = { a: 1, b: 2 };

varHello = React.createClass({
    render: function() {
        return<div><pre>{JSON.stringify(data, null, 2) }</pre></div>;
    }
});

React.render(<Hello />, document.getElementById('container'));

Working example.

Update

classPrettyPrintJsonextendsReact.Component {
    render() {
         // data could be a prop for example// const { data } = this.props;return (<div><pre>{JSON.stringify(data, null, 2) }</pre></div>);
    }
}

ReactDOM.render(<PrettyPrintJson/>, document.getElementById('container'));

Example

Stateless Functional component, React .14 or higher

constPrettyPrintJson = ({data}) => {
    // (destructured) data could be a prop for examplereturn (<div><pre>{ JSON.stringify(data, null, 2) }</pre></div>);
}

Or, ...

constPrettyPrintJson = ({data}) => (<div><pre>{ 
    JSON.stringify(data, null, 2) }</pre></div>);

Working example

Memo / 16.6+

(You might even want to use a memo, 16.6+)

constPrettyPrintJson = React.memo(({data}) => (<div><pre>{
    JSON.stringify(data, null, 2) }</pre></div>));

Solution 2:

Just to extend on the WiredPrairie's answer a little, a mini component that can be opened and closed.

Can be used like:

<Pretty data={this.state.data}/>

enter image description here

exportdefaultReact.createClass({

    style: {
        backgroundColor: '#1f4662',
        color: '#fff',
        fontSize: '12px',
    },

    headerStyle: {
        backgroundColor: '#193549',
        padding: '5px 10px',
        fontFamily: 'monospace',
        color: '#ffc600',
    },

    preStyle: {
        display: 'block',
        padding: '10px 30px',
        margin: '0',
        overflow: 'scroll',
    },

    getInitialState() {
        return {
            show: true,
        };
    },

    toggle() {
        this.setState({
            show: !this.state.show,
        });
    },

    render() {
        return (
            <divstyle={this.style}><divstyle={this.headerStyle}onClick={this.toggle }><strong>Pretty Debug</strong></div>
                {( this.state.show ?
                    <prestyle={this.preStyle}>
                        {JSON.stringify(this.props.data, null, 2) }
                    </pre> : false )}
            </div>
        );
    }
});

Update

A more modern approach (now that createClass is on the way out)

import styles from'./DebugPrint.css'import autoBind from'react-autobind'import classNames from'classnames'importReactfrom'react'exportdefaultclassDebugPrintextendsReact.PureComponent {
  constructor(props) {
    super(props)
    autoBind(this)
    this.state = {
      show: false,
    }
  }    

  toggle() {
    this.setState({
      show: !this.state.show,
    });
  }

  render() {
    return (
      <divstyle={styles.root}><divstyle={styles.header}onClick={this.toggle}><strong>Debug</strong></div>
        {this.state.show 
          ? (
            <prestyle={styles.pre}>
              {JSON.stringify(this.props.data, null, 2) }
            </pre>
          )
          : null
        }
      </div>
    )
  }
}

And your style file

.root {
    backgroundColor: '#1f4662';
    color: '#fff';
    fontSize: '12px';
}

.header {
    backgroundColor: '#193549';
    padding: '5px 10px';
    fontFamily: 'monospace';
    color: '#ffc600';
}

.pre {
    display: 'block';
    padding: '10px 30px';
    margin: '0';
    overflow: 'scroll';
}

Solution 3:

The 'react-json-view' provides solution rendering json string.

importReactJsonfrom'react-json-view';
<ReactJsonsrc={my_important_json}theme="monokai" />

Solution 4:

constgetJsonIndented = (obj) => JSON.stringify(newObj, null, 4).replace(/["{[,\}\]]/g, "")

constJSONDisplayer = ({children}) => (
    <div><pre>{getJsonIndented(children)}</pre></div>
)

Then you can easily use it:

constDemo = (props) => {
   ....
   return <JSONDisplayer>{someObj}<JSONDisplayer>
}

Solution 5:

TLDR

Pretty Print JSON in React

<pre>{JSON.stringify(data, null, 2)}</pre>

Post a Comment for "Pretty Printing Json With React"