首页 > 解决方案 > 删除nodejs中json键名中的特殊字符

问题描述

我收到一个解析的 excel json,键名有 . $,我想删除那些。(我无法更改 excel 文件上的任何内容)

在我的第一刻,我尝试解析为字符串并使用正则表达式,但我无法更改任何值。

有什么建议么?

代码示例:

{"example1.":"sometext.","example2.":"anothertext."}

我不想

{"example1":"sometext.","example2":"anothertext."}

我创建了一个函数来处理这个错误,如果有人知道更好的答案,我会很高兴。

const KeyNameinJson = (json, callback) => {
let newJson = {};
let PropertyNames = Object.getOwnPropertyNames(json);
let async = require('async');
async.each(PropertyNames, (key, callback) => {
    let newKey = key.replace(/[|&;$%@."<>()+,]/g, "");
    newJson[newKey] = json[key];
    callback();
}, () => {
    callback(newJson);
});

};

标签: node.jsjson

解决方案


我不知道你为什么需要async这个任务。这可以通过更简单的方式实现吗?

'use strict';

const obj1 = {"example1.":"sometext.","example2.":"anothertext."};
const obj2 = {};

for (const key of Object.getOwnPropertyNames(obj1)) {
  obj2[key.replace(/[|&;$%@."<>()+,]/g, "")] = obj1[key];
}

console.log(obj2);


推荐阅读