Home > Enterprise >  Finding a string in json object Node JS
Finding a string in json object Node JS

Time:11-05

I have a json file in which I have to find a string is available of not.

Example:

   let testjson =require('./jsontest.json');
   let string= 'abcd';

I would like to find if abcd in json object.

My json file looks like following

[
 { 
   name:"aaaa",
   j1:[ "abcd","efg"],
   j2:[ "abcde","xyz"]
 },
 { 
   name:"bbbbb",
   j1:[ "abcdw","efg1"],
   j2:[ "abcde12","xyz22"]
 }
]

Please let me know how to fix this issue in Node js

CodePudding user response:

You can use filter or some method to find the given string is present or not in the array.

Major difference between these method is filter return the matched object or an empty array if no match and some return true if any one one of item matches the condition or false.

More on MDN

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; }

CodePudding user response:

The example that you have given have objects and string in the json file. You can use a recursive function to search for a string within a JSON object and you can use includes to check if if has the string or not, something like:

  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 .`);
    }

replace testjson with your JSON object and searchString with the string you want to search for in your json .

  • Related