Javascript 使用 React 打印漂亮的 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30765163/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pretty Printing JSON with React
提问by Brandon
I'm using ReactJS and part of my app requires pretty printed JSON.
我正在使用 ReactJS,我的应用程序的一部分需要漂亮的打印 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:
我得到一些 JSON 如下:{ "foo": 1, "bar": 2 },如果我JSON.stringify(obj, null, 4)在浏览器控制台中运行它,它会打印得很漂亮,但是当我在这个反应片段中使用它时:
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".
它呈现粗略的 JSON,看起来像"{ \"foo\" : 2, \"bar\": 2}\n".
How do I get those characters to be interpreted properly? {
如何正确解释这些字符?{
回答by WiredPrairie
You'll need to either insert BRtag appropriately in the resulting string, or use for example a PREtag so that the formatting of the stringifyis retained:
您需要BR在结果字符串中适当地插入标记,或者使用例如PRE标记以便stringify保留的格式:
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'));
工作示例。
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'));


Stateless Functional component, React .14 or higher
无状态功能组件,React .14 或更高版本
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>);
Memo / 16.6+
备忘录 / 16.6+
(You might even want to use a memo, 16.6+)
(您甚至可能想使用备忘录,16.6+)
const PrettyPrintJson = React.memo(({data}) => (<div><pre>{
JSON.stringify(data, null, 2) }</pre></div>));
回答by Chris
Just to extend on the WiredPrairie's answer a little, a mini component that can be opened and closed.
只是稍微扩展一下 WiredPrairie 的答案,一个可以打开和关闭的迷你组件。
Can be used like:
可以像这样使用:
<Pretty data={this.state.data}/>
export default React.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 (
<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)
一种更现代的方法(现在 createClass 即将淘汰)
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 { backgroundColor: '#1f4662'; color: '#fff'; fontSize: '12px'; }
.root { backgroundColor: '#1f4662'; 颜色:'#fff'; 字体大小:'12px'; }
.header { backgroundColor: '#193549'; padding: '5px 10px'; fontFamily: 'monospace'; color: '#ffc600'; }
.header { backgroundColor: '#193549'; 填充:'5px 10px'; fontFamily: '等宽'; 颜色:'#ffc600'; }
.pre { display: 'block'; padding: '10px 30px'; margin: '0'; overflow: 'scroll'; }
.pre { 显示:'块'; 填充:'10px 30px'; 边距:'0'; 溢出:'滚动'; }
回答by Aborn Jiang
The 'react-json-view' provides solution rendering json string.
' react-json-view' 提供了渲染 json 字符串的解决方案。
import ReactJson from 'react-json-view';
<ReactJson src={my_important_json} theme="monokai" />
回答by Ben Carp
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>
}
回答by caot
Here is a demo react_hooks_debug_print.htmlin react hooks that is based on Chris's answer. The json data example is from https://json.org/example.html.
这是一个react_hooks_debug_print.html基于 Chris 回答的 react hooks演示。json 数据示例来自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 DebugPrintwith the follows:
并替换DebugPrint为以下内容:
const DebugPrint = () => {
// https://stackoverflow.com/questions/30765163/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>
)
}

