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
One approach would be to find the string, than count the number of new lines before it this way:
Also on JSFiddle.
Please note, as defined here:
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:
I add code below.
I think it’ll works as you want and can help you even a little.
Thanks.