我在我的节点应用程序中有几个 json 文件(可以超过 10 个)的文件夹,我需要从验证方面读取它们并找到特定属性,如果该属性出现在多个 json 文件中,则会引发错误,这是什么从性能和效率方面做到这一点的最佳方式
例如,我的名为 plugins 的文件夹和所有 json 的构建方式如下
json1
{
"action": [
{
"delete": {
"path": "deleteFile",
"providedAction":"Del"
},
{
"update": {
"path": "updateFile",
"providedAction":"UPD"
}
}
]
}
Run Code Online (Sandbox Code Playgroud)
这是有效的json,因为providedAction = add在其他json 中不存在**
json2
{
"action": [
{
"add": {
"path": "addFile",
"providedAction":"Add"
}
}
]
}
Run Code Online (Sandbox Code Playgroud)
这不是有效的json,因为providedAction = UPD 操作已经存在 JSON 3
{
"action": [
{
{
"update": {
"path": "updateFile",
"providedAction":"UPD"
}
}
]
}
Run Code Online (Sandbox Code Playgroud)
我需要验证只有这个 json 有动作“Del”,如果不止一个 json 有这个 trow 错误,建议如何做?
Luc*_*nti 11
好的,这是代码。如果你不明白什么让我知道,我很乐意帮助你!
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);
}
})
});
});
});
Run Code Online (Sandbox Code Playgroud)
JSON 1:
{"action": [
{
"delete": {
"path": "deleteFile",
"providedAction": "Del"
}
},
{
"update": {
"path": "updateFile",
"providedAction": "UPD"
}
}
]
}
Run Code Online (Sandbox Code Playgroud)
JSON 2:
{
"action": [
{
"add": {
"path": "addFile",
"providedAction": "Add"
}
}
]
}
Run Code Online (Sandbox Code Playgroud)
JSON 3:
{
"action": [
{
"update": {
"path": "updateFile",
"providedAction": "UPD"
}
}
]
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14763 次 |
| 最近记录: |