node.js - 解析/格式化 api 响应(nodejs/express)
问题描述
我目前正在为从 API 返回的响应对象的大小/格式而苦苦挣扎。
我只是经常发现很难在我的节点终端中看到响应的嵌套对象 - 跟踪可能有几百行的缩进似乎相当难以管理,以至于我认为我一定做错了什么?
我可以使用任何标准做法或有用的工具吗?JSON.stringify()稍微好一点,因为至少我可以看到整个响应,但它只是一堵文字墙,所以有点相反的问题。
如果这很明显,请道歉!
解决方案
您可以从本机节点模块使用 util inspect :
// Node.js syntax to demonstrate
// the util.inspect() method
// Importing util library
const util = require('util');
// Object
const nestedObject = {};
nestedObject.a = [nestedObject];
nestedObject.b = [['a', ['b']], 'b', 'c', 'd'];
nestedObject.b = {};
nestedObject.b.inner = nestedObject.b;
nestedObject.b.obj = nestedObject;
// Inspect by basic method
console.log("1.>", util.inspect(nestedObject));
// Random class
class geeksForGeeks { }
// Inspecting geeksForGeeks class
console.log("2.>", util.inspect(new geeksForGeeks()));
// Inspect by passing options to method
console.log("3.>", util.inspect(
nestedObject, true, 0, false));
// Inspect by calling option name
console.log("4.>", util.inspect(nestedObject,
showHidden = false, depth = 0, colorize = true));
// Inspect by passing in JSON format
console.log("5.>", util.inspect(nestedObject,
{ showHidden: false, depth: 0, colorize: true }));
// Inspect by directly calling inspect from 'util'
const { inspect } = require('util');
// Directly calling inspect method
// with single property
console.log("6.>", inspect(nestedObject),
{ colorize: true });
// Directly passing the JSON data
console.log("7.>", util.inspect([
{ name: "Amit", city: "Ayodhya" },
{ name: "Satyam", city: "Lucknow" },
{ name: "Sahai", city: "Lucknow" }],
false, 3, true));
// Directly calling inspect method with single property
console.log("8.>", inspect(nestedObject), { depth: 0 });
资料来源:[https://www.geeksforgeeks.org/node-js-util-inspect-method/]
推荐阅读
- python - 如何在数据类中解决重复的类名?
- reactjs - React Multiple Checkboxes 在更改后不可见
- r - 如何在一列中创建唯一值并合并第二列中的所有其他值?
- reactjs - React with TypeScript 项目包含 JS 编写的文件
- python - 蟒蛇 | 之前使用打印值
- javascript - 在不了解它的情况下获取 DOM-Element
- c# - MVC 个人用户区
- opencv - OpenCV找到这个图像的轮廓来裁剪和旋转
- r - 插入符号包中使用预测概率的自定义性能函数
- java - org.mockito.exceptions.misusing.UnfinishedStubbingException' 异常。无法评估 mypackage.MockedService$MockitoMock$980936084.toString()