在 NodeJS 中遍历 JSON 文件

Iterating through JSON file in NodeJS

我正在尝试遍历 json 文件,其中这是文件的模板:

[
    {
        "REF_DATE": 2016,
        "GEO": "Canada",
        "DGUID": "2016A11124",
        "Educational qualification": "Career, technical or professional training certificate",
        "Field of study": "Total, field of study",
        "Gender": "Total, gender",
        "Age group": "15 to 64 years",
        "Status of student in Canada": "Canadian and international students",
        "Characteristics after graduation": "Graduates reporting employment income",
        "Graduate statistics": "Number of graduates",
        "UOM": "Number",
        "UOM_ID": 223,
        "SCALAR_FACTOR": "units",
        "SCALAR_ID": 0,
        "VECTOR": "v1007923968",
        "COORDINATE": "1.2.1.1.1.1.4.1",
        "VALUE": 33930,
        "STATUS": "",
        "SYMBOL": "",
        "TERMINATED": "",
        "DECIMALS": 0
    },
    {
        "REF_DATE": 2016,
        "GEO": "Canada",
        "DGUID": "2016A11124",
        "Educational qualification": "Career, technical or professional training certificate",
        "Field of study": "Education [1]",
        "Gender": "Total, gender",
        "Age group": "15 to 64 years",
        "Status of student in Canada": "Canadian and international students",
        "Characteristics after graduation": "Graduates reporting employment income",
        "Graduate statistics": "Number of graduates",
        "UOM": "Number",
        "UOM_ID": 223,
        "SCALAR_FACTOR": "units",
        "SCALAR_ID": 0,
        "VECTOR": "v1007929890",
        "COORDINATE": "1.2.2.1.1.1.4.1",
        "VALUE": 865,
        "STATUS": "",
        "SYMBOL": "",
        "TERMINATED": "",
        "DECIMALS": 0
    }
]

我基本上想查看整个文档,并且仅将这些对象中的某些元素(“教育资格”和“VALUE”)拉入数组,如果它们符合某些条件(具有相同的“研究领域" 和 "UOM_ID")。我想在 get api 请求中 return 这个数组。

我目前有一个帮助函数来读取json文件:

function jsonReader(dataAddress, cb) {
    fs.readFile(dataAddress, (err, fileData) => {
      if (err) {
        return cb && cb(err);
      }
      try {
        const object = JSON.parse(fileData);
        return cb && cb(null, object);
      } catch (err) {
        return cb && cb(err);
      }
    });
}

我还有一个写入的获取请求,当前 return 是整个 json 文件。

app.get('/income/:job', (req, res)=>{
    
    jsonReader('./data.json', (err, result) => {
        if(err){
            console.log(err);
        } else {
            res.send(result);
        }
    })

});

我能得到一些关于如何完成这项任务的帮助吗?我试过浏览许多 youtube 视频和论坛,但找不到太多帮助。非常感谢!

因此您已经设法从文件中以文本形式读取数据,然后使用 JSON.parse( ) 将其转换为对象。这是一个好的开始。

有两种方法可以做到这一点,这里是我经常使用的一种方法 often.You 可以使用 Object.keys( ) 来获取对象中所有 属性 名称的列表。然后,只需创建一个新对象,并将所需的键和属性从原始对象复制到它即可。此示例将结果放在新对象而不是数组中,但使用数组在很大程度上没有什么不同,除非您想使用数字索引。

var output = {};
var keys = Object.keys(object);
var key = null;
for (key of Keys){
      if(key === "MATCHING_PROPERTY_NAME")
            if(object[key] === "MATCHING_VALUE")
                   output[key]= object[key];
}