在React中,我试图将从服务器获得的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}]"
我想用换行符和空格使它成为可读的数据。
这是我的快速功能
<Typography>
{{JSON.parse(item.api_text).map((item) => {
console.log(item);
return `<br>${JSON.stringify(item, null, 't')}</br>`;
})} }
</Typography>
此处item.api_text是上面的字符串。我知道这会造成错误,但我想要这样的东西。感谢
编辑:我想在文档上这样显示它,而不是在控制台中。
[{
"mat_type": 1,
"mat_title": "Title1",
"mat_unit": 2,
"mat_price": 44000,
"mat_cost": 2000
},
{
"mat_type": 2,
"mat_title": "Title2",
"mat_unit": 2,
.....
尝试这个
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>
创建html
<Typography id="json" style= "white-space: pre-wrap;">
</Typography>
输出
[
{
"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
}
]
多亏了@eevolutionxbox,我找到了一种在react中实现这一点的方法。
在我的react组件内部。pre在保存下一行方面做得很好。
<pre>
{JSON.stringify(JSON.parse(item.api_text), null, 3)}
</pre>
另一种选择,样式可以赋予被称为空白的标签:"预包装",感谢@Serge。我使用了<code/>让它看起来更好
<Typography id='json' style={{whiteSpace: 'pre-wrap'}}>
<code>
{JSON.stringify(JSON.parse(item.api_text), null, 3)}
</code>
</Typography>