Pretty Printing JSON with React
Asked Answered
F

7

201

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 browser console, it pretty prints, but when I use it in this react snippet:

render: function() {
  var json = this.getStateFromFlux().json;
  return (
    <div>
      <JsonSubmitter onSubmit={this.onSubmit} />
      { JSON.stringify(json, null, 2) }
    </div>
  );
},

it renders gross JSON that looks like "{ \"foo\" : 2, \"bar\": 2}\n".

How do I get those characters to be interpreted properly? {

Fourflush answered 10/6, 2015 at 19:6 Comment(3)
Have you tried JSON.stringify(json, null, "\t") ?Grimes
It turns out I had a silly error whereby this.getStateFromFlux().json was already returning a string. I modified it to hold a JS object instead, and it now works flawlessly.Fourflush
see also github.com/alexkuz/react-json-treeRepose
B
358

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 };

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

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

Working example.

Update

class PrettyPrintJson extends React.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

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

Or, ...

const PrettyPrintJson = ({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+)

const PrettyPrintJson = React.memo(({data}) => (<div><pre>{
    JSON.stringify(data, null, 2) }</pre></div>));
Beat answered 10/6, 2015 at 20:8 Comment(2)
Thanks for this! Didn't know about the optional JSON.stringify-parameter. Javascript is awesome ^^Induna
This is perfect - the simplest solution is always the best! I recommend adding highlight.js for some syntax highlighting and theming pizzazz.Ummersen
M
55

TLDR

Pretty Print JSON in JavaScript and React

<pre>{JSON.stringify(data, null, 2)}</pre>
Magocsi answered 8/12, 2021 at 21:17 Comment(2)
Simplicity is key. Thanks!Kierakieran
doesn't work if your data contain BigIntBenitabenites
N
31

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

export default React.createClass({

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

    headerStyle: {
        background-color: '#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 (
            <div style={this.style}>
                <div style={this.headerStyle} onClick={ this.toggle }>
                    <strong>Pretty Debug</strong>
                </div>
                {( this.state.show ?
                    <pre style={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'
import React from 'react'

export default class DebugPrint extends React.PureComponent {
  constructor(props) {
    super(props)
    autoBind(this)
    this.state = {
      show: false,
    }
  }    

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

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

And your style file

.root {
    background-color: #1f4662;
    color: #fff;
    font-size: 12px;
}

.header {
    background-color: #193549;
    padding: 5px 10px;
    font-family: monospace;
    color: #ffc600;
}

.pre {
    display: block;
    padding: 10px 30px;
    margin: 0;
    overflow: scroll;
}
Nola answered 11/2, 2016 at 13:0 Comment(7)
This is awesome +1 for sure! I make little things like this for debugging and testing data prior to building the component itself out. This one is really awesome!Giblets
To convert to component: toddmotto.com/react-create-class-versus-componentSapota
I like how the style is another key on the component classEpithalamium
btw, in the CSS file are you not forgot to remove the Apostrophes '' around the valuesEpithalamium
@perymimon good point! updated. Need to update it for a functional component tooNola
@Nola after I run it I note you should convert CSS camelCase to kabab-case. but besides that, it works very well. good jobEpithalamium
@perymimon good catch, fixed! need a PR system built in SO :)Nola
T
18

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

import ReactJson from 'react-json-view';
<ReactJson src={my_important_json} theme="monokai" />
Tupungato answered 29/3, 2018 at 2:41 Comment(0)
E
10
const getJsonIndented = (obj) => JSON.stringify(newObj, null, 4).replace(/["{[,\}\]]/g, "")

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

Then you can easily use it:

const Demo = (props) => {
   ....
   return <JSONDisplayer>{someObj}<JSONDisplayer>
}
Euchre answered 24/7, 2019 at 16:0 Comment(0)
C
1

Short and Simple

<div>
  <pre dangerouslySetInnerHTML={{
     __html: JSON.stringify(data, null, 2),
  }} />
</div>
Cropeared answered 22/9, 2021 at 18:5 Comment(1)
⚠️ Heads up to XSS vulnerability in dangerouslySetInnerHTML. If you choose this approach, make sure to sanitize the data contentEquality
P
0

Here is a demo react_hooks_debug_print.html in react hooks that is based on Chris's answer. The json data example is from https://json.org/example.html.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello World</title>
    <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

    <!-- Don't use this in production: -->
    <script src="https://unpkg.com/[email protected]/babel.min.js"></script>
  </head>
  <body>
    <div id="root"></div>
    <script src="https://raw.githubusercontent.com/cassiozen/React-autobind/master/src/autoBind.js"></script>

    <script type="text/babel">

let styles = {
  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', }
}

let data = {
  "glossary": {
    "title": "example glossary",
    "GlossDiv": {
      "title": "S",
      "GlossList": {
        "GlossEntry": {
          "ID": "SGML",
          "SortAs": "SGML",
          "GlossTerm": "Standard Generalized Markup Language",
          "Acronym": "SGML",
          "Abbrev": "ISO 8879:1986",
          "GlossDef": {
            "para": "A meta-markup language, used to create markup languages such as DocBook.",
            "GlossSeeAlso": [
              "GML",
              "XML"
            ]
          },
          "GlossSee": "markup"
        }
      }
    }
  }
}

const DebugPrint = () => {
  const [show, setShow] = React.useState(false);

  return (
    <div key={1} style={styles.root}>
    <div style={styles.header} onClick={ ()=>{setShow(!show)} }>
        <strong>Debug</strong>
    </div>
    { show 
      ? (
      <pre style={styles.pre}>
       {JSON.stringify(data, null, 2) }
      </pre>
      )
      : null
    }
    </div>
  )
}

ReactDOM.render(
  <DebugPrint data={data} />, 
  document.getElementById('root')
);

    </script>

  </body>
</html>

Or in the following way, add the style into header:

    <style>
.root { background-color: #1f4662; color: #fff; fontSize: 12px; }
.header { background-color: #193549; padding: 5px 10px; fontFamily: monospace; color: #ffc600; }
.pre { display: block; padding: 10px 30px; margin: 0; overflow: scroll; }
    </style>

And replace DebugPrint with the follows:

const DebugPrint = () => {
  // https://mcmap.net/q/127258/-pretty-printing-json-with-react
  const [show, setShow] = React.useState(false);

  return (
    <div key={1} className='root'>
    <div className='header' onClick={ ()=>{setShow(!show)} }>
        <strong>Debug</strong>
    </div>
    { show 
      ? (
      <pre className='pre'>
       {JSON.stringify(data, null, 2) }
      </pre>
      )
      : null
    }
    </div>
  )
}
Phosphoresce answered 27/6, 2019 at 2:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.