jquery - 使用 jsonpath 进行字符串搜索

标签 jquery json jsonpath

我有一个巨大的 JSON 文件,其中包含超过 20000 个对象。我想查询这个 json 文件中的字符串。但是,使用 jsonpath,我只能找到完全匹配的内容?

假设我的文件如下:

{ "store": {
    "book": [ 
      { "category": "reference",
        "author": "Nigel Rees",
        "title": "Sayings of the Century",
        "price": 8.95
      },
      { "category": "fiction",
        "author": "Evelyn Waugh",
        "title": "Sword of Honour",
        "price": 12.99
      },
      { "category": "fiction",
        "author": "Herman Melville",
        "title": "Moby Dick",
        "isbn": "0-553-21311-3",
        "price": 8.99
      },
      { "category": "fiction",
        "author": "J. R. R. Tolkien",
        "title": "The Lord of the Rings",
        "isbn": "0-395-19395-8",
        "price": 22.99
      }
    ],
    "bicycle": {
      "color": "red",
      "price": 19.95
    }
  }
}

我想做的是:

jsonPath(data, "$..book[?(@.title like 'ord')]")

并获取标题中带有“ord”的书籍。

{ "category": "fiction",
        "author": "J. R. R. Tolkien",
        "title": "The Lord of the Rings",
        "isbn": "0-395-19395-8",
        "price": 22.99
      }
{ "category": "fiction",
        "author": "Evelyn Waugh",
        "title": "Sword of Honour",
        "price": 12.99
}

这可能吗?

最佳答案

更新:

根据the unit teststhis answer ,您可以在表达式中嵌入正则表达式文字,它将被评估。以下是单元测试的示例。

$.menu.items[?(@ && @.label && /SVG/.test(@.label))].id

因此,对于您的示例,它将是:

$.store.book[ ?( @ && @.title && /ord/.test(@.title) ) ].isbn

我对一些相当大的 json 文件(2-3MB)使用了 jsonPath,它们是我们应用程序速度变慢的原因。如果您非常关心性能,我建议为您想要搜索的每个字段创建一个补充索引。这样做还可以让您加权每个字段的相关性值,这对于获得良好的搜索结果非常重要。

或者更好的是,如果您预计您的应用程序可能会增长,您可能需要使用服务器端搜索引擎( http://sphinxsearch.com/ 或 SAAS 版本 http://indexden.com/ )。

对于您的具体问题,应该支持 like 运算符。然而,我已经能够仅使用字符串数组(例如数据结构中的标题)并使用纯 JavaScript 正则表达式( http://www.w3schools.com/jsref/jsref_obj_regexp.asp )来实现相当好的性能。

关于jquery - 使用 jsonpath 进行字符串搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18107322/

相关文章:

javascript - 如何使这个 if 语句起作用?

c# - 如何使用 Jquery Mobile 在 MVC 中动态创建带有 Count Bubbles 的链接

java - 如何判断InputStream中是否包含JSON数据?

java - Jsonpath 在 Spring Boot 测试中为嵌套 JSON 对象返回 null

Jquery addclass(),如何处理类冲突

javascript - 导航 jQuery

r - 将不等长列表的列表转换为数据帧

ios - 从 JSON 中一张一张加载照片

java - JsonPath:按数组中任意数组中的值进行过滤

java - JSON PATH 字段 NULL 检查表达式