En React, intento convertir los datos JSON que obtengo del servidor en datos legibles.
Aquí está la cadena del servidor.
"[{\"mat_type\":1,\"mat_title\":\"Title1\",\"mat_unit\":2,\"mat_price\":44000,\"mat_cost\":2000},{\"mat_type\":2,\"mat_title\":\"Title2\",\"mat_unit\":2,\"mat_price\":44000,\"mat_cost\":2000},{\"mat_id\":1,\"mat_title\":\"Title\",\"mat_unit\":2,\"mat_price\":4400,\"mat_cost\":2000,\"mat_status\":0}]"Quiero que sean datos legibles con nueva línea y espaciado.
Aquí está mi función rápida
<Typography> {{JSON.parse(item.api_text).map((item) => { console.log(item); return `<br>${JSON.stringify(item, null, '\t')}</br>`; })} } </Typography>Aquí item.api_text es la cadena de arriba. Sé que esto creará un error, pero quiero algo como esto. Gracias
Editar: quiero mostrarlo así en el documento, no en la consola.
[{ "mat_type": 1, "mat_title": "Title1", "mat_unit": 2, "mat_price": 44000, "mat_cost": 2000 }, { "mat_type": 2, "mat_title": "Title2", "mat_unit": 2, .....chicos, gracias a @evolutionxbox, encontré una manera de hacer esto en reaccionar.
aquí dentro de mi componente de reacción. pre funciona muy bien para preservar la siguiente línea.
<pre> {JSON.stringify(JSON.parse(item.api_text), null, 3)} </pre>Otra alternativa, se puede dar estilo a las etiquetas conocidas como espacios en blanco: 'pre-wrap', gracias a @Serge. He usado </code/> para que se vea mejor
<Typography id='json' style={{whiteSpace: 'pre-wrap'}}> <code> {JSON.stringify(JSON.parse(item.api_text), null, 3)} </code> </Typography>prueba esto
var json="[{\"mat_type\":1,\"mat_title\":\"Title1\",\"mat_unit\":2,\"mat_price\":44000,\"mat_cost\":2000},{\"mat_type\":2,\"mat_title\":\"Title2\",\"mat_unit\":2,\"mat_price\":44000,\"mat_cost\":2000},{\"mat_id\":1,\"mat_title\":\"Title\",\"mat_unit\":2,\"mat_price\":4400,\"mat_cost\":2000,\"mat_status\":0}]"; <script type="text/javascript"> $(document).ready(function () { var jo=JSON.parse(json); json=JSON.stringify(jo,null,4); $("#json").html(json); }); </script>crear html
<Typography id="json" style= "white-space: pre-wrap;"> </Typography>producción
[ { "mat_type": 1, "mat_title": "Title1", "mat_unit": 2, "mat_price": 44000, "mat_cost": 2000 }, { "mat_type": 2, "mat_title": "Title2", "mat_unit": 2, "mat_price": 44000, "mat_cost": 2000 }, { "mat_id": 1, "mat_title": "Title", "mat_unit": 2, "mat_price": 4400, "mat_cost": 2000, "mat_status": 0 } ]