查詢json數(shù)據(jù)結(jié)構(gòu)的8種方式
你有沒(méi)有對(duì)“在復(fù)雜的JSON數(shù)據(jù)結(jié)構(gòu)中查找匹配內(nèi)容”而煩惱。這里有8種不同的方式可以做到:
JsonSQL
JsonSQL實(shí)現(xiàn)了使用SQL select語(yǔ)句在json數(shù)據(jù)結(jié)構(gòu)中查詢的功能。
- jsonsql.query("select * from json.channel.items order by title desc",json);
主頁(yè): http://www.trentrichardson.com/jsonsql/
JSONPath
JSONPath就像是針對(duì)JSON數(shù)據(jù)結(jié)構(gòu)的XPath。
例子:
- jsonPath( books, '$..book[(@.length-1)]')
主頁(yè): http://goessner.net/articles/JsonPath/
jfunk
jFunk允許你檢索(很快會(huì)加入管理功能)復(fù)雜的JSON或Javascript對(duì)象。jFunk API的設(shè)計(jì)幾乎與jQuery API類似。它直接復(fù)制了jQuery的API,除了那些針對(duì)DOM的API。
例子:
- Jf("> vegetables > *[color=Orange]",Food).get();
主頁(yè): http://code.google.com/p/jfunk/
TaffyDB
你過(guò)去有沒(méi)有注意到Javascript對(duì)象的字面值看起來(lái)很像記錄?如果你把他們包裹在一個(gè)數(shù)組里面,那么它們看起來(lái)有沒(méi)有像一個(gè)數(shù)據(jù)庫(kù) 表?TaffyDB是一個(gè)Javascript庫(kù),它提供了強(qiáng)大的數(shù)據(jù)庫(kù)功能以實(shí)現(xiàn)之前的想法,大大改善了你在Javascript中使用數(shù)據(jù)的方式。
- var kelly = friends({id:2}).first();
主頁(yè): http://www.taffydb.com/
linq.js
linq.js——Javascript中的LINQ(譯者注:.Net中的概念,見(jiàn) http://msdn.microsoft.com/zh-tw/library/bb397897)
- var queryResult2 = Enumerable.From(jsonArray)
- .Where("$.user.id < 200")
- .OrderBy("$.user.screen_name")
- .Select("$.user.screen_name + ':' + $.text")
- .ToArray();
主頁(yè): http://linqjs.codeplex.com/
主頁(yè): http://neue.cc/reference.htm
objeq
objeq是一個(gè)簡(jiǎn)單的庫(kù),實(shí)現(xiàn)了對(duì)POJSO(Plain-Old JavaScript Objects,普通的Javascript對(duì)象)的實(shí)時(shí)查詢。
- var res = $objeq(data, "age > 40 && gender == 'female' -> name");
- // --> Returns ['Jessica']
主頁(yè): https://github.com/agilosoftware/objeq
(譯注:它使用了Javascript的property setters,所以它只能工作在較新的 瀏覽器上)
json:select()
使用類CSS選擇符來(lái)查詢JSON。
- .lang:val("Bulgarian") ~ .level
主頁(yè): http://jsonselect.org/#tryit
Paul的編程珠璣中的Javascript數(shù)組過(guò)濾方法
- var a = [1,2,3,4,5,6,7,8,9,10];
- // return everything
- a.where( "( ) => true" ) ;
- // --> [1,2,3,4,5,6,7,8,9,10]
- // return even numbers
- a.where( "( n, i ) => n % 2 == 0" ) ;
- // --> [2,4,6,8,10]
- // query first 6 products whose category begins with 'con' using extra param and regular expression
- products.where( "( el, i, res, param ) => res.length <= 6 && param.test( el.cat )", /^con/i);
- // using customer table data from SQL Server's northwind database...
- customers.where( "( el, i, res, param ) => el.country == param", "USA" );
主頁(yè): http://www.paulfree.com/28/javascript-array-filtering/#more-28
目前這是我最喜歡的查詢JSON數(shù)據(jù)結(jié)構(gòu)的方法。它非常的簡(jiǎn)單,并且據(jù)作者所說(shuō)它非常快。
它背后的理念和 John Resig的JavaScript Micro-Templating類似:使用正確表達(dá)式將一段非常簡(jiǎn)單的字符串轉(zhuǎn)換成Javascript函數(shù)。
當(dāng)然,還有更多強(qiáng)大的解決方案。 Paul實(shí)現(xiàn)的原型還缺少對(duì)過(guò)濾表達(dá)式的語(yǔ)法檢查,但是我相信你應(yīng)該可以自己解決Javscript的語(yǔ)法檢查。
***,你必須決定哪個(gè)對(duì)于你的項(xiàng)目來(lái)說(shuō)***。
原文鏈接:http://itindex.net/detail/41114-json-%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84