node.js - 如何在 node.js 中过滤和格式化 json?
问题描述
我想在我的 Nodejs 服务器中格式化一个 JSON 对象。删除一些字段,重命名一些字段,移动一些字段。
我有许多不同的模式需要应用于许多不同的 JSON,所以我希望有一个可以解析配置文件的库。
也许像这样的配置文件:
DELETE request.logid
DELETE request.data.*.time
MOVE request.data.images data.images
之前的 JSON 应用了上述模式:
{
"request": {
"data": {
"book": {
"name": "Hello World",
"time": 1546269044490
},
"images": [
"a-book.jpg"
]
},
"logid": "a514-afe1f0a2ac02_DCSix"
}
}
申请后:
{
"request": {
"data": {
"book": {
"name": "Hello World"
}
}
},
"data": {
"images": [
"a-book.jpg"
]
}
}
它在哪里?
我知道写一个函数可以直接做同样的事情,但问题是我有太多不同的模式和太多不同的 JSON,所以我想通过配置文件而不是 js 函数来管理它们。
解决方案
是的,你可以做这样的事情......
// Note: psuedocode
// Read the configuration file;
const commands = (await readFile('config')).split('\r\n').split(' ');
// your original JSON;
const obj = {...};
// Modify the JSON given the commands
commands.forEach( row=>{
if(row[0]==="DELETE"){
delete obj[row[1]];
}else if(row[0]==="MOVE"){
// use lodash to make your life easier.
_.set(obj,`${row[2]}`,_.get(obj,`${row[1]}`));
delete obj[row[1]];
}else if(...){
...
}
})
推荐阅读
- maven - 特定测试套件的 Maven 运行命令
- java - 在 Springboot 中添加 @EnableWebMvc 会将日期输出从字符串更改为数组
- laravel-5.5 - 邮件发送失败且没有错误
- javascript - 结帐页面上的 BigCommerce 自定义 javascript 不起作用
- javascript - 无法获取按钮的 onclick 属性来调用 JS 函数
- c - 以相反的顺序打印数组指针值
- mysql - MySQL 回馈许多值
- javascript - 桌面应用程序加密与具有客户端加密的 Web 应用程序
- node.js - TypeORM实体继承ManyToOne关系
- pc-lint - uint8_t、uint16_t 和 uint32_t 在 PCLint 中无法识别