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

时间:2018-03-16 18:04:45

标签: javascript

我正在尝试编写一个读取JSON文件的JavaScript函数,并通过将值与用户输入字符串匹配来检索信息。为了导航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”数组。将变量替换为谓词似乎不起作用。

1 个答案:

答案 0 :(得分:1)

您的变量替换是错误的。尝试使用template literal之类的。

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