我有一个 JSON 和一个目标字符串。我想在 JSON 文件中搜索目标字符串的所有键并获取匹配的行号。
{
"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]"
}
例如,如果我的目标字符串是mobile,那么它应该返回有key mobile的行号,即第13行。
我尝试使用一个简单的 for 循环,但随后我可能需要使用递归,它会变得过于复杂,有什么我可以使用的库吗?
一种方法是找到字符串,然后以这种方式计算它之前的新行数:
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 );
也在JSFiddle