0

我无法提取 JSON 信息。我的 JSON 文件包含一部小说的 100 章。每章都包含该章中的许多字符。

例如:

{"ONE": ["PERSON A", "PERSON B", "PERSON C", "PERSON D", "PERSON A"],
"TWO": ["PERSON A", "PERSON D", "PERSON F", "PERSON G", "PERSON H"],
"THREE": ["PERSON F", "PERSON D", "PERSON A", "PERSON A", "PERSON A"]
... "ONE HUNDRED": ["PERSON B", "PERSON A"]
}

我的目标是设计一种方法来提取两个字符在整本书中同时出现的次数,而两个字符在一章中只能同时出现一次。例如,在 100 章内,我想知道 PERSON A 和 PERSON B 共出现了多少次。

我有两种方法,A. 使用 JSON PATH 并过滤掉数据集(其中 PERSON A 和 B 共同出现),并计算它们共同出现的章节数。(我也不知道要查询什么:P) B. 虽然我不太擅长 JAVASCRIPT。我的想法是定义一个整数,然后在 JSON 文件的每一章中运行 for 循环。

我想知道你们是否可以在这方面与我分享你的知识!谢谢!

4

2 回答 2

0

可能会选择@Kinglish 的答案,但为了完整起见,我想添加它。

正确的 JSON 路径尚无此语法,但我们正在构建官方规范,因此现在是提出建议的最佳时机。实际上,我们最近一直在研究要支持的表达式语法。我在解释该提案的评论中引用了这个问题。

于 2021-07-18T21:30:45.077 回答
0

这是一个函数,您可以在其中指定是否需要计数或章节数组

这是分解的功能

const cooccur = (people, rettype) => {
  let result = Object.keys(
  // the final result will be an array of object keys
     Object.fromEntries(Object.entries(chapters)
     // but to iterate your object, we need to first convert it into an array with Object.entries
     // then with that result, convert it back into an object with Object.fromEntries
        .filter(c => people.filter(r => c[1].indexOf(r) > -1).length === people.length)));
         // this double filter will run through each chapter and filter it based on the second filter's result
         // the second filter takes our people array and finds how many total occurences of both people in a given chapter
         // if the total number of occurences equals the number of people we're searching for, it's a match
  return rettype === 'count' ? result.length : result;
}

let chapters = {
  "ONE": ["PERSON A", "PERSON B", "PERSON C", "PERSON D", "PERSON A"],
  "TWO": ["PERSON A", "PERSON D", "PERSON F", "PERSON G", "PERSON H"],
  "THREE": ["PERSON F", "PERSON D", "PERSON A", "PERSON A", "PERSON A"],
  "ONE HUNDRED": ["PERSON B", "PERSON A"]
}

const cooccur = (people, rettype) => {
  let result = Object.keys(Object.fromEntries(Object.entries(chapters).filter(c => people.filter(r => c[1].indexOf(r) > -1).length === people.length)));
  return rettype === 'count' ? result.length : result;
}

console.log('number of occurences:', cooccur(["PERSON A", "PERSON B"], 'count'));
console.log('occurence chapters:', cooccur(["PERSON A", "PERSON B"], 'chapters'));

于 2021-07-18T19:31:57.797 回答