首页 > 解决方案 > 如何在 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 函数来管理它们。

标签: node.jsjson

解决方案


是的,你可以做这样的事情......

// 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(...){
    ...
  }
})

推荐阅读