我在我的节点应用程序中有几个json文件的文件夹(可能超过10个)我需要从验证方面读取它们并查找特定属性,如果此属性出现在多个json文件中则抛出错误,从绩效和效率方面
来做到这一点的最佳方式是什么?例如我的文件夹名为plugins 并且所有json都构建如下
json1
{
"action": [
{
"delete": {
"path": "deleteFile",
"providedAction":"Del"
},
{
"update": {
"path": "updateFile",
"providedAction":"UPD"
}
}
]
}
这是有效的json ,因为 providedAction = add不存在在其他json **
json2
{
"action": [
{
"add": {
"path": "addFile",
"providedAction":"Add"
}
}
]
}
这是无效 json,因为 providedAction = UPD操作已经存在 JSON 3
{
"action": [
{
{
"update": {
"path": "updateFile",
"providedAction":"UPD"
}
}
]
}
我需要验证只有这个json有动作“Del”,如果多个json有这个trow错误,它的建议是怎么做的?
答案 0 :(得分:3)
好的,这是代码。如果你不明白的事情让我知道,我很乐意帮助你!
var glob = require("glob");
var fs = require("fs");
var _inArray = function(needle, haystack) {
for(var k in haystack) {
if(haystack[k] === needle) {
return true;
}
}
return false;
}
glob("json/*.json", function(err, files) { // read the folder or folders if you want: example json/**/*.json
if(err) {
console.log("cannot read the folder, something goes wrong with glob", err);
}
var matters = [];
files.forEach(function(file) {
fs.readFile(file, 'utf8', function (err, data) { // Read each file
if(err) {
console.log("cannot read the file, something goes wrong with the file", err);
}
var obj = JSON.parse(data);
obj.action.forEach(function(crud) {
for(var k in crud) {
if(_inArray(crud[k].providedAction, matters)) {
// do your magic HERE
console.log("duplicate founded!");
// you want to return here and cut the flow, there is no point in keep reading files.
break;
}
matters.push(crud[k].providedAction);
}
})
});
});
});
JSON 1:
{"action": [
{
"delete": {
"path": "deleteFile",
"providedAction": "Del"
}
},
{
"update": {
"path": "updateFile",
"providedAction": "UPD"
}
}
]
}
JSON 2:
{
"action": [
{
"add": {
"path": "addFile",
"providedAction": "Add"
}
}
]
}
JSON 3:
{
"action": [
{
"update": {
"path": "updateFile",
"providedAction": "UPD"
}
}
]
}
答案 1 :(得分:2)
不是我写过的最漂亮的代码,但现在是:
// Require the nodejs file system library
var fs = require('fs');
var path = '/usr/local/var/jsons';
var delCounter = 0;
// Readdir reads a path and gives an array of filenames
// to the callback handleFiles.
fs.readdir(path, handleFiles);
function handleFiles (err, files) {
if (err) throw err;
var i;
var jsonFilePattern=/\.[json]+$/i;
var fileName;
var filePath;
// Tells fs to read an utf-8 file.
var fileReadOptions = {
'encoding':'utf-8'
};
for (i = 0; i < files.length; ++i) {
fileName = files[i];
// Check if the file has a .json extension
if (fileName.match(jsonFilePattern)) {
filePath = path + '/' + fileName;
// Open the file as utf-8 and call handleJsonFile back
// when done reading.
fs.readFile(filePath, fileReadOptions, handleJsonFile);
}
}
}
function handleJsonFile (err, data) {
if (err) throw err;
var dataObject = JSON.parse(data);
var i;
var action;
// Loop through all possible action.
for (i = 0; i < dataObject.action.length; ++i) {
action = dataObject.action[i];
if (action.delete &&
action.delete.providedAction &&
action.delete.providedAction === 'Del')
{
// If there is a 'Del', add it to the counter.
++delCounter;
}
}
if (delCounter > 1) {
throw new Exception('Jsons not valid.');
}
}
答案 2 :(得分:1)
或许这样的事情,享受!
npm install glob
JSON 1
module.exports = {
"action": [{
"delete": {
"path": "deleteFile",
"action":"Del"
}
}]
}
CODE
(function() {
var glob = require("glob");
glob("path/to/*.js", function(er, files) {
if(er) return;
var x = 0;
files.forEach(function(file) {
require(file)['action'].forEach(function(act) {
if(act.delete.action && act.delete.action == "Del") x++;
});
});
if(x > 1) throw new Exception(""); // or something ja!
});
})();
凌晨5点没有睡觉,抱歉如果我犯了错误,我只想告诉你的方式......不要复制粘贴!的xD。
答案 3 :(得分:0)
使用现代语法,在这里减少和扩展可能会有很大帮助:
const files = readdirSync(path);
files.reduce((acc, curr) => {
const file = JSON.parse(readFileSync(path.join(path, curr), 'utf8'));
const merged = { ...acc, ...file };
// Check for destructive merging.
if (Object.keys(file).length + Object.keys(acc).length > Object.keys(merged).length) {
throw Error('Destructive merge of JSON files.');
}
return merged;
}, {});