【问题标题】:String search with jsonpath使用 jsonpath 进行字符串搜索
【发布时间】:2013-08-09 01:29:10
【问题描述】:

我有一个巨大的 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
}

有可能吗?

【问题讨论】:

    标签: jquery json jsonpath


    【解决方案1】:

    更新:

    根据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) 来实现相当不错的性能。

    【讨论】:

    • 感谢您的回复。但是我在 jsonpath 中找不到“like”运算符?你的意思是不支持吗?
    • 我错了。显然不支持 LIKE 运算符。但是,我确实在 jsonPath 单元测试中找到了正则表达式文字的用法。我已经更新了链接到该用法的答案。
    • 请注意,这是使用 eval 来处理此解决方案。因此,如果您使用用户提交的数据进行搜索,很可能是这种情况,您将不得不担心正确过滤和转义输入,以便恶意用户无法代表其他用户执行代码(或者如果这个 jsonPath 通过 node.js 或其他东西在服务器端运行)。
    猜你喜欢
    • 2015-12-12
    • 2014-03-06
    • 2015-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-13
    • 2019-03-20
    相关资源
    最近更新 更多