[英]How to read json file and filter the result
I am stacked since 7 days in a simple function in javascript... but i can not find the soluction!我在 javascript 中的简单 function 中堆叠了 7 天......但我找不到解决方案!
The problem is this: I have to read a json file, and filter the result...问题是这样的:我必须阅读 json 文件,然后过滤结果......
This is my server-side script for read the file:这是我用于读取文件的服务器端脚本:
function testing(email)
{
let rawdata = fs.readFileSync('test.json');
var mydata = JSON.parse(rawdata);
console.log("parse:"+ mydata);
const value = email;
const result = mydata.filter(email);
console.log("result: " + result);
if(result == 'undefined')
{
return(false);
}
else
{
return(true);
}
};
This is my json file:这是我的 json 文件:
[
{
"1":"black@gmail.com"
},
{
"2":"bad@gmail.com"
}
{
"3":"strangemail@gmail.com"
}
]
That JSON data structure is rather odd, with a different key in each object, but if that's what you're stuck with, here's how it can be handled. JSON 数据结构相当奇怪,每个 object 中都有不同的键,但如果这就是你所坚持的,这就是它的处理方法。
// a string to stand in for JSON fie: const jsonStr = `[ {"1":"black@gmail.com"}, {"2":"bad@gmail.com"}, {"3":"strangemail@gmail.com"} ]`; function testing(email) { var mydata = JSON.parse(jsonStr); const result = mydata.filter(obj => { // search every property in object for email, since the // source JSON data doesn't have consistent keys for (let [key, value] of Object.entries(obj)) { if (value === email) { return true; } } }); console.log(result); // [ { '2': 'bad@gmail.com' } ] return result.length > 0; } let example = testing("bad@gmail.com"); console.log(example); // true
Every element of json array should contain the same consistent key and if you need index, index should be another key ie: const myData = [{"idx": 1, "email": "black@gmail.com"}, {"idx": 2, "email": "bad@gmail.com"}, {"idx": 3, "email": "strangemail@gmail.com"}]
json 数组的每个元素都应该包含相同的一致键,如果需要索引,索引应该是另一个键,即:
const myData = [{"idx": 1, "email": "black@gmail.com"}, {"idx": 2, "email": "bad@gmail.com"}, {"idx": 3, "email": "strangemail@gmail.com"}]
And then you could filter data using the expression as然后你可以使用表达式过滤数据
const result = myData.filter((x) => x.email === email);
Result should be something like:结果应该是这样的:
[{"idx": 1, "email": "black@gmail.com"}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.