1. 程式人生 > >Web前端工作筆記002---json資料查詢的方法_json查詢大全,JsonSQL資料查詢,jfunk資料查詢

Web前端工作筆記002---json資料查詢的方法_json查詢大全,JsonSQL資料查詢,jfunk資料查詢

json資料查詢的方法

網上看到有一篇帖子,有8種json資料查詢的方法,大家可以研究一下,我現在分享一下!

JsonSQL

JsonSQL實現了使用SQL select語句在json資料結構中查詢的功能。

例子:

$.getJSON("testjson.js", function(a){
    console.dir(jsonsql.query("select * from json.channel.items order by title desc,json",a));
});

JSONPath

JSONPath就像是針對JSON資料結構的XPath。

例子:

jsonPath( books, '$..book[(@.length-1)]')

jfunk

jFunk允許你檢索(很快會加入管理功能)複雜的JSON或Javascript物件。jFunk API的設計幾乎與jQuery API類似。它直接複製了jQuery的API,除了那些針對DOM的API。

例子:

jF("*[color=Orange]",Food).get();
jF("> vegetables > *[color=Orange]",Food).get();

TaffyDB

你過去有沒有注意到Javascript物件的字面值看起來很像記錄?如果你把他們包裹在一個數組裡面,那麼它們看起來有沒有像一個數據庫表?TaffyDB是一個Javascript庫,它提供了強大的資料庫功能以實現之前的想法,大大改善了你在Javascript中使用資料的方式。

var kelly = friends({id:2}).first();

linq.js

var queryResult2 = Enumerable.From(jsonArray)
    .Where("$.user.id < 200")
    .OrderBy("$.user.screen_name")
    .Select("$.user.screen_name + ':' + $.text")
    .ToArray();

objeq

objeq是一個簡單的庫,實現了對POJSO(Plain-Old JavaScript Objects,普通的Javascript物件)的實時查詢。

var res = $objeq(data, "age > 40 && gender == 'female' -> name");
    // --> Returns ['Jessica']

(譯註:它使用了Javascript的property setters,所以它只能工作在較新的瀏覽器上)

json:select()

使用類CSS選擇符來查詢JSON。

.lang:val("Bulgarian") ~ .level

Paul的程式設計珠璣中的Javascript陣列過濾方法

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" );

json查詢 專案背景和應用

專案背景

做一個微信專案,需要對返回的json資料進行搜尋和查詢,查詢是模糊查詢,json資料結構比較複雜。

應用

我一開始用的是JsonSQL,可以進行簡單的json資料查詢,比較方便,但是用起來發現JsonSQL查詢的json資料結構比較簡單,對於複雜的,巢狀很多的資料,用起來不是很方便。因此,對於JsonSQL,我最後沒有用它。

JsonSQL的應用:

function getAll(){
                $.getJSON("testjson.js", function(a){
                    console.dir(jsonsql.query("select * from json.channel.items order by title desc,json",a));
                });
    }

 function getFiltered(){
                $.getJSON("testjson.js", function(json){
                    console.dir(jsonsql.query("select title,url,author,category from json.channel.items where (category=='javascript' || author=='trent') order by title,category asc limit 3",json));
                });
}

function getLimit(){
                $.getJSON("testjson.js", function(json){
                    console.dir(jsonsql.query("select url from json.channel.items where (category=='javascript' && author=='trent') order by url asc limit 1,2",json));
                });
    }

引進的是如下2個檔案。

<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<script type="text/javascript" src="jsonsql-0.1.js"></script>

testjson.js的結構是

{
    "channel": {
        "title": "Trent's Blog",
        "link": "http://www.haorooms.com/",
        "description": "practical programming",
        "published": "Fri, 28 Dec 20014 04:27:29 +0000",
        "language": "en",
        "items": [{
            "title": "Are You Using Regular Expressions Within SQL?",
            "url": "http://www.haorooms.com/?p=45",
            "published": "Fri, 28 Dec 2014 02:32:31 +0000",
            "author": "trent",
            "category": "programming",
            "guid": {
                "isPermaLink": false,
                "url": "http://www.haorooms.com/?p=45"
            },
            "description": "Are You Using Regular Expressions Within SQL?Are You Using Regular Expressions Within SQL?Are You Using Regular Expressions Within SQL?"
        },{
            "title": "Nothing Better than a Good Dump!",
            "url": "http://www.haorooms.com/?p=44",
            "published": "Mon, 24 Dec 2013 02:54:39 +0000",
            "author": "trent",
            "category": "javascript",
            "guid": {
                "isPermaLink": false,
                "url": "http://www.haorooms.com/?p=44"
            },
            "description": "Nothing Better than a Good Dump!Nothing Better than a Good Dump!Nothing Better than a Good Dump!Nothing Better than a Good Dump!Nothing Better than a Good Dump!"
        }]
    }
}

JsonSQL對這種簡單的資料結構,查詢起來比較方便。注意:jsonSQL的程式碼得知:

parse: function(json,ops){
        var o = { fields:["*"], from:"json", where:"", orderby:[], order: "asc", limit:[] };
        for(i in ops) o[i] = ops[i];

        var result = [];        
        result = this.returnFilter(json,o);
        result = this.returnOrderBy(result,o.orderby,o.order);
        result = this.returnLimit(result,o.limit);

        return result;
    },

JsonSQl只支援簡單的SQL查詢,例如where,orderBy,order,且where只能跟“==”不能進行模糊查詢!不能用like,否則會出錯!!!

另外,JsonSQl的鍵值key只能是英文,不能有中文,否則會出錯!!!

jfunk的應用:

可以對比較複雜的資料結構進行操作

var Food={
    fruits: [
        { name: "Banana", color: "Yellow" },
        { name: "Apple", color: "Red" },
        { name: "Grapefruit", color: "Orange" },
        { name: "Kiwi", color: "Green" }
        ],
    vegetables: [
        { name: "Carrot", color: "Orange" },
        { name: "Turnip", color: "Purple" },
        { name: "Rutabaga", color: "Yellow" },
        { name: "Sweet Potato", color: "Orange" }
        ]
    };

var orangeStuff=jF("*[color=Orange]",Food).get();
var orangeVeg  =jF("> vegetables > *[color=Orange]",Food).get();

//orange stuff is now [{name:"Grapefruit",color:"Orange"},{name:"Carrot",color:"Orange"},{name:"Sweet Potato",color:"Orange"}]
//orange veg is now [{name:"Carrot",color:"Orange"},{name:"Sweet Potato",color:"Orange"}]

專案應用

因為我的資料很複雜,最後我選用的是jfunk,但是我沒有完全運用jfunk,我只是用jF("> vegetables > *[color]",Food).get();這種方法,查詢到了vegetables 子類中的所有color,並對color的某些屬性,迴圈判斷,模糊查詢屬性中有沒有某個值,然後把查詢到的結果push到了新的陣列當中。這樣完成的搜尋結果。