我有一个很大的JSON文件,该文件由无法修改的另一个进程生成。如果值为空白,则该过程会将“ null”作为这些属性的值。
并且我需要在我的 Nodejs 服务器端将这些“空”值视为空,否则将其视为文字字符串。我想看看JSON.parser(fs.readFileSync('...'))
是否可以读取文件并创建具有null
而不是"null"
的那些属性的局部变量。
答案 0 :(得分:-1)
实现此目标的正确方法是根据JSON.parse()documentation使用reviver
函数:
let string = '{"key1": "value1", "key2": "null"}';
let json = JSON.parse(string, function reviver(key, value) {
if (value === 'null')
return null;
return value;
});
console.log(json);
答案 1 :(得分:-2)
检查this答案。
不要将'null'
替换为null
。
如此:
// test.json content:
{
"test": "null",
"test2": "null",
"test3": null,
"test4": [1, null, "null", 2, "3"]
}
// index.js content:
const fs = require('fs');
const source = fs.readFileSync('test.json', 'utf8');
const fixedJson = source.replace(/"null"/g, 'null');
const fixedObject = JSON.parse(fixedJson);
console.log(fixedJson);
console.log(fixedObject);
console.log(fixedObject.test3 === null);