gpt4 book ai didi

javascript - 如何将 JavaScript 变量替换为 JSPath 表达式

转载 作者:行者123 更新时间:2023-11-30 20:40:28 28 4
gpt4 key购买 nike

我正在尝试编写一个 JavaScript 函数来读取 JSON 文件,并通过将值与用户输入的字符串进行匹配来检索信息。为了导航 JSON 文件,我使用了 JSPath,但是我不知道如何使用函数在 JSPath 谓词中传递的字符串变量。

这是我目前拥有的代码:

function retrieveCategoryWinners(query) {
var category = query
var jsonDoc = $.getJSON("nobel.json")
var winners = JSPath.apply('.prizes{.category === $query}.laureates', jsonDoc,
{query: category})

JSON 文件的片段:

{
"prizes": [
{
"year": "2017",
"category": "physics",
"laureates": [
{
"id": "941",
"firstname": "Rainer",
"surname": "Weiss",
"motivation": "\"for decisive contributions to the LIGO detector and the observation of gravitational waves\"",
"share": "2"
},
{
"id": "942",
"firstname": "Barry C.",
"surname": "Barish",
"motivation": "\"for decisive contributions to the LIGO detector and the observation of gravitational waves\"",
"share": "4"
},
{
"id": "943",
"firstname": "Kip S.",
"surname": "Thorne",
"motivation": "\"for decisive contributions to the LIGO detector and the observation of gravitational waves\"",
"share": "4"
}
]
}

因此,例如,如果查询参数是“physics”,JSPath 将返回“laureates”数组。不过,将变量代入谓词似乎行不通。

最佳答案

您的变量替换是错误的。试试 template literal像这样。

  var winners = JSPath.apply(`.prizes{.category === "${category}"}.laureates`, js,
{query: category})

关于javascript - 如何将 JavaScript 变量替换为 JSPath 表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49327011/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com