提问人:SANAL RAJ 提问时间:11/3/2023 最后编辑:Yuvaraj MSANAL RAJ 更新时间:11/3/2023 访问量:25
在 json 对象 Node JS 中查找字符串
Finding a string in json object Node JS
问:
我有一个json文件,我必须在其中找到一个字符串是可用的。
例:
let testjson =require('./jsontest.json');
let string= 'abcd';
我想在json对象中找到if。abcd
我的json文件如下所示
[
{
name:"aaaa",
j1:[ "abcd","efg"],
j2:[ "abcde","xyz"]
},
{
name:"bbbbb",
j1:[ "abcdw","efg1"],
j2:[ "abcde12","xyz22"]
}
]
请让我知道如何在 Node js 中解决此问题
答:
0赞
Yuvaraj M
11/3/2023
#1
您可以使用 or 方法来查找给定的数组中是否存在。filter
some
string
这些方法之间的主要区别在于,如果没有匹配,则返回匹配或空数组,如果其中任何一个项目与条件匹配,则返回。filter
object
some
true
false
const json = [
{
name:"aaaa",
j1:[ "abcd","efg"],
j2:[ "abcde","xyz"]
},
{
name:"bbbbb",
j1:[ "abcdw","efg1"],
j2:[ "abcde12","xyz22"]
},
{
name:"aaaa2",
j1:[ "abcds","efg"],
j2:[ "abcd","xyz"]
},
]
const string = "abcd"
const result = json.filter(data=>{
const {j1,j2} = data;
return j1.includes(string) || j2.includes(string)
});
console.log(result); // return the matched object
const isFound = json.some(data=>{
const {j1,j2} = data;
return j1.includes(string) || j2.includes(string)
});
console.log(isFound); // return boolean
.as-console-wrapper { max-height: 100% !important; }
0赞
Sahil bakoru
11/3/2023
#2
您给出的示例在 json 文件中具有对象和字符串。您可以使用递归函数在 a 中搜索字符串,并可用于检查是否有该字符串,如下所示:JSON object
includes
const fs = require('fs')
function searchJson(obj, targetString) {
for (const key in obj) {
if (typeof obj[key] === 'object') {
if (searchJson(obj[key], targetString)) {
return true;
}
} else if (typeof obj[key] === 'string' && obj[key].includes(targetString)) {
return true;
}
}
return false;
}
const testjson = require('./jsontest.json');
const searchString = 'abcd';
const isStringFound = searchJson(testjson, searchString);
if (isStringFound) {
console.log(`The string '${searchString}' is found.`);
} else {
console.log(`The string '${searchString}' is not found .`);
}
替换为您的 JSON 对象和要在 JSON 中搜索的字符串。testjson
searchString
评论