繁体   English   中英

如何设置 JSON 响应的样式/格式并以用户可读的格式显示?

[英]How to style/format JSON response and display it in user readable format?

我正在做一个个人项目,一个邮递员克隆。 我正在使用 fetch API 来获取数据,然后使用 JSON.stringify() 将其转换为字符串并将其显示在“textarea”中,即“响应”字段,如下所示。 遇到了一个答案-https://stackoverflow.com/questions/2614862/how-can-i-beautify-json-programmatically ,但它似乎对我不起作用。

如何格式化 json 对象或字符串并将其显示在“响应”选项卡中?

邮递员回应

**Here is the html code for the response field**
<div class="responseBox">
    Response
    <textarea class="responseText" id="responseId" ></textarea>
</div>

**JS code for fetching the response using Fetch API and displaying it in Response field :** 
const response = await fetch(url);
console.log("Fetching data...");
const e = await response.json();
console.log(e);
responseId.innerText=JSON.stringify(e);

**CSS for response field :** 
.responseText{
width: 705px;
height: 350px;
position: relative;
right: 255px;
white-space: pre;

}

正如您链接的答案所暗示的那样, JSON.stringify函数支持格式化 JSON 字符串,这就是您应该格式化 JSON 字符串的方式。

JSON.stringify(jsObj, null, "\t"); // stringify with tabs inserted at each level
JSON.stringify(jsObj, null, 4);    // stringify with 4 spaces at each level

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM