2013-08-07 80 views
1

我有超過20000個對象的巨大JSON文件。我想在這個json文件中查詢一個字符串。但是,使用jsonpath,我只能找到完全匹配?使用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 
} 

是否有可能?

回答

4

更新:

根據the unit teststhis answer,你可以嵌入在表達字面一個正則表達式,它將被evaled。以下是單元測試的例子。

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

所以,你的榜樣,那就是:

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

我用jsonPath一段相當大的JSON文件(2-3MB),他們是我們的應用程序的原因放慢。如果你關心的是性能,我建議爲每個你想要搜索的領域創建一個補充索引。這樣做也可以讓您加權每個領域的相關性值,這對獲得良好的搜索結果非常重要。或者更好的是,如果您預計您的應用程序可能會增長,您可能需要招待服務器端搜索引擎(http://sphinxsearch.com/或SAAS版本http://indexden.com/)。

至於你的具體問題,類運算符應該被支持。不過,我只用一串字符串(例如數據結構中的標題)並使用普通的javascript正則表達式(http://www.w3schools.com/jsref/jsref_obj_regexp.asp)就能夠獲得相當不錯的性能。

+0

感謝您的回覆。但是我在jsonpath中找不到「like」運算符?你的意思是不支持? – huzeyfe

+1

我錯了。顯然LIKE運算符不被支持。但是,我確實在jsonPath單元測試中找到了正則表達式的用法。我已更新了該鏈接的答案。 – Homer6

+1

請注意,這是使用eval來處理此解決方案。因此,如果您使用用戶提交的數據進行搜索(可能是這種情況),您將不得不擔心正確過濾和轉義輸入,以致惡意用戶無法代表其他用戶執行代碼(或者如果這個jsonPath通過node.js在服務器端運行)。 – Homer6