Simplify Couchdb JSON response

自古美人都是妖i 提交于 2019-12-03 06:50:25

问题


I'm storing location data in Couchdb, and am looking for a way to get an array of just the values, instead of key: value for every record. For example:

The current response

{"total rows": 250, "offset": 0, "rows":[
    {"id": "ec5de6de2cf7bcac9a2a2a76de5738e4", "key": "user1", "value": {"city": "San Francisco", "address":"1001 Bayhill Dr"},
    {"id": "ec5de6de2cf7bcac9a2a2a76de573ae4","key": "user1", "value": {"city": "Palo Alto", "address":"583 Waverley St"}
    ... (etc).
]}

I only really need:

[{"city": "San Francisco", "address":"1001 Bayhill Dr"},
 {"city": "Palo Alto", "address":"583 Waverley St"},
 ...]

The reason for all this is to minimize the amount of bandwidth that a JSON response consumes. I can't seem to find a way to transform the view into a simple array. Any suggestions?

Thanks.


回答1:


You can use _show and _list functions, they take either a document or a view (respectively) and can send back a transformed response in whatever format you need. (in this case, JSON)

Update: I ran a simple test with the data you provided here on my own CouchDB. Here's the list function I ended up writing. Customize it to fit your needs. :)

function (head, req) {
    // specify that we're providing a JSON response
    provides('json', function() {
        // create an array for our result set
        var results = [];

        while (row = getRow()) {
            results.push({
                city: row.value.city,
                address: row.value.address
            });
        }

        // make sure to stringify the results :)
        send(JSON.stringify(results));
    });
}


来源:https://stackoverflow.com/questions/4949689/simplify-couchdb-json-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!