skip to Main Content

I have a JSON and a target string. I want to search the all the keys in the JSON file for the target string and get the line number where there is a match.

{
  "name": "John Doe",
  "age": 30,
  "occupation": "Software Engineer",
  "address": {
    "street": "123 Main Street",
    "city": "Anytown",
    "state": "CA",
    "zip": "98765"
  },
  "phone": {
    "home": "(123) 456-7890",
    "mobile": "(987) 654-3210"
  },
  "email": "[email protected]"
}

For example if my target string is mobile, then it should return the line number where there is a key mobile, which is 13th line.

I tried using a simple for loop but then I might need to use recursion and it will become overly complex, are there any libraries I could use?

2

Answers


  1. One approach would be to find the string, than count the number of new lines before it this way:

    let file=`{
      "name": "John Doe",
      "age": 30,
      "occupation": "Software Engineer",
      "address": {
        "street": "123 Main Street",
        "city": "Anytown",
        "state": "CA",
        "zip": "98765"
      },
      "phone": {
        "home": "(123) 456-7890",
        "mobile": "(987) 654-3210"
      },
      "email": "[email protected]"
    }`;
    function getLine( match, search ) {
        let index = search.indexOf(match);
        let split = search.substring(0, index);
        let lines = split.split('n').length;
        console.log( lines );
        return lines;
    }
    getLine( 'mobile', file );

    Also on JSFiddle.

    Please note, as defined here:

    JavaScript Object Notation (JSON) is a standard text-based format for
    representing structured data based on JavaScript object syntax

    Additionally, as commented below, to convert JSON Object into a string, kind of pretty-print with new lines and tabs, we can use JS stringify() method, which accepts 3 arguments:

    JSON.stringify(obj, false, "t")
    
    Login or Signup to reply.
  2. I add code below.

    const obj = {
      name: "John Doe",
      age: 30,
      occupation: "sfd",
      address: {
        detail: {
          other1: 123,
          other2: 345,
        },
        street: "123 Maif",
        city: "Anytown",
        state: "CA",
        zip: "98765",
      },
      phone: {
        home: "(123) 456-7890",
        mobile: "(987) 654-3210",
      },
      email: "[email protected]",
    };
    
    const getKeys = (object) =>
      typeof object !== "object"
        ? []
        : [
            ...Object.keys(object).reduce((keys, key) => [...keys, key, ...getKeys(object[key])],[]),
            "",
          ];
    const line = getKeys(obj).indexOf("email");
    

    I think it’ll works as you want and can help you even a little.

    Thanks.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search