问题描述
我有这个标准化的 API 响应:
{
"result": "123","entities": {
"articles": {
"123": {
"id": "123","author": "1","title": "My awesome blog post","comments": [
"324"
]
}
},"users": {
"1": {
"id": "1","name": "Paul"
},"2": {
"id": "2","name": "Nicole"
}
},"comments": {
"324": {
"id": "324","commenter": "2"
}
}
}
}
除了与 console.log()
一起使用的 JSON.stringify()
之外,是否有更好的方法来可视化/记录/调试(已经标准化或正在标准化)响应?
解决方法
实际上有很多 NPM 模块,例如 pretty-print-json 或 json-beautify 可以为您以及所有库执行此操作,尽管我最喜欢的漂亮打印方法仍然是与 console.log() 配对JSON.stringify() 因为您可以轻松地在控制台中使用其余参数进行美化。
JSON.stringify() 为您提供一个 replacer 和一个 space 参数:
- replacer 允许您将所需的属性保留在字符串化对象中,因此他会找到该属性并将其保留在字符串中;
- 空格 定义了制表,用于在输出 JSON 字符串中插入空格,仅用于可读性。