xpath或Defiant.js并获取节点信息

时间:2015-09-17 18:30:54

标签: javascript object xpath

我有我的json:

{
  "data": {
    "header": {
      "version": 1,
      "last_updated": "2015-09-16T14:09:22Z"
    },
    "frequent" : {
      "keywords": [
        {
          "keyword":"roi",
          "keyword":"subjectrecord",
          "keyword":"evidence",
          "keyword":"case",
          "keyword":"account",
          "keyword":"supervisor",
          "keyword":"legacy tecs"
        }
      ]
    },
    "body": {
      "items": [
        {
          "item": {
            "type": "pdf",
            "title": "title 1",
            "updated_time": "2015-09-16T14:09:22Z",
            "keywords": [
              {
                "keyword":"supervisor"
              },
              {
                "keyword":"manager"
              },
              {
                "keyword":"title 1"
              }
            ]
          }
        },
        {
          "item": {
            "type": "pdf",
            "title": "title 2",
            "updated_time": "2015-09-16T14:09:22Z",
            "keywords": [
              {
                "keyword":"supervisor"
              }
            ]
          }
        },
        {
          "item": {
            "type": "pdf",
            "title": "title 3",
            "updated_time": "2015-09-16T14:09:22Z"
          }
        }
      ]
    }
  }
}

我希望能够做的是搜索" body"并返回与关键字匹配的任何项目。例如,如果我搜索"主管"我的结果应该是这样的:

"item": {
        "type": "pdf",
        "title": "title 1",
        "updated_time": "2015-09-16T14:09:22Z",
        "keywords": [
          {
            "keyword":"supervisor"
          },
          {
            "keyword":"manager"
          },
          {
            "keyword":"title 1"
          }
        ]
      }
    },
    {
      "item": {
        "type": "pdf",
        "title": "title 2",
        "updated_time": "2015-09-16T14:09:22Z",
        "keywords": [
          {
            "keyword":"supervisor"
          }
        ]
      }
    }

执行以下操作只会返回关键字。

var results = JSON.search(potentials, '//*[keyword="'+query+'"]');

1 个答案:

答案 0 :(得分:0)

在查询结尾处插入/ ..

var results = JSON.search(potentials, '//*[keyword="'+query+'"]/..');