Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

162
Views
Bastante imprimiendo JSON con React

Estoy usando ReactJS y parte de mi aplicación requiere JSON bastante impreso.

Obtengo algo de JSON como: { "foo": 1, "bar": 2 } , y si lo ejecuto a través JSON.stringify(obj, null, 4) en la consola del navegador, se imprime bastante, pero cuando lo uso en este fragmento de reacción:

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

representa un JSON bruto que se parece a "{ \"foo\" : 2, \"bar\": 2}\n" .

¿Cómo hago para que esos caracteres se interpreten correctamente? {

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Deberá insertar la etiqueta BR de manera adecuada en la cadena resultante o usar, por ejemplo, una etiqueta PRE para que se conserve el formato de la 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'));

Ejemplo de trabajo .

Actualizar

 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'));

Ejemplo

Componente funcional sin estado, React .14 o superior

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

O, ...

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

ejemplo de trabajo

Notas / 16.6+

(Puede que incluso quieras usar una nota, 16.6+)

 const PrettyPrintJson = React.memo(({data}) => (<div><pre>{ JSON.stringify(data, null, 2) }</pre></div>));
over 4 years ago · Santiago Trujillo Report

0

Solo para ampliar un poco la respuesta de WiredPrairie, un mini componente que se puede abrir y cerrar.

Se puede utilizar como:

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

ingrese la descripción de la imagen aquí

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

Actualizar

Un enfoque más moderno (ahora que createClass está a punto de desaparecer)

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

Y tu archivo de estilo

 .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; }
over 4 years ago · Santiago Trujillo Report

0

El ' react-json-view ' proporciona una solución que representa la cadena json.

 import ReactJson from 'react-json-view'; <ReactJson src={my_important_json} theme="monokai" />
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!