使用字符串搜索 JSON 并在 javascript 中获取行号

Search JSON with a string and get the line number in javascript

提问人:bob piper 提问时间:11/14/2023 最后编辑:mitikobob piper 更新时间:11/15/2023 访问量:46

问:

我有一个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”,那么它应该返回第 13 行。

我尝试使用简单的for循环,但是我可能需要使用递归,它会变得过于复杂,有没有可以使用的库?

json javascript 对象

评论

0赞 mitiko 11/14/2023
这个线程可能会有所帮助:stackoverflow.com/questions/6946466/...

答:

1赞 skobaljic 11/14/2023 #1

一种方法是找到字符串,而不是以这种方式计算它前面的新行数:

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 上。

请注意,定义如下

JavaScript 对象表示法 (JSON) 是一种基于文本的标准格式,用于 基于 JavaScript 对象语法表示结构化数据

此外,如下所述,要将 JSON 对象转换为带有新行和制表符的字符串,我们可以使用 JS stringify() 方法,它接受 3 个参数:

JSON.stringify(obj, false, "\t")

评论

1赞 Adrid 11/14/2023
你的答案是不正确的。 不是字符串,而是对象。所以你不能用 .如果使用 将其转换为字符串,则将删除所有内容。file\nJSON.stringify\n
0赞 Johannes Stadler 11/14/2023
JSON.stringify有一个可选的第三个参数,所以如果你使用例如,你应该得到换行符,答案应该再次起作用。spaceJSON.stringify(file, null, 2)
1赞 skobaljic 11/14/2023
@Adrid 在你之前没有人提到过这个物体。他说,不在JSON对象中。读取文件意味着将内容存储到字符串中 - 使其成为 JSON 对象需要方法。您可以在此处阅读有关它的更多信息。I want to search the all the keys in the JSON fileJSON.parse
0赞 Adrid 11/14/2023 #2

我在下面添加代码。

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");

我认为它会随心所欲地工作,甚至可以为您提供一点帮助。

谢谢。