In React I'm trying to render the JSON data I'm getting from the server to readable data.
Here is the string from the server
"[{\"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}]"
I want to make it readable data with newline and spacing on it.
Here is my quick function
<Typography>
{{JSON.parse(item.api_text).map((item) => {
console.log(item);
return `<br>${JSON.stringify(item, null, '\t')}</br>`;
})} }
</Typography>
Here item.api_text is the string above. I know this will create error but I want something like this. Thanks
Edit: I want to display it like this on document not in console.
[{
"mat_type": 1,
"mat_title": "Title1",
"mat_unit": 2,
"mat_price": 44000,
"mat_cost": 2000
},
{
"mat_type": 2,
"mat_title": "Title2",
"mat_unit": 2,
.....
CodePudding user response:
try this
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>
create html
<Typography id="json" style= "white-space: pre-wrap;">
</Typography>
output
[
{
"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
}
]
CodePudding user response:
guys thanks to @evolutionxbox i've found a way to do this in react.
here inside my react component. pre works very well in preserving the next line.
<pre>
{JSON.stringify(JSON.parse(item.api_text), null, 3)}
</pre>
Another alternative, style can be given to the tags known as white-space: 'pre-wrap', Thanks to @Serge. I've used </code/> to make it look better
<Typography id='json' style={{whiteSpace: 'pre-wrap'}}>
<code>
{JSON.stringify(JSON.parse(item.api_text), null, 3)}
</code>
</Typography>
