简化Couchdb JSON响应

时间:2011-02-09 19:46:20

标签: json couchdb transformation

我正在将位置数据存储在Couchdb中,我正在寻找一种方法来获取一个只有值的数组,而不是每个记录的key:value。例如:

当前回复

{"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).
]}

我真的需要:

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

所有这一切的原因是最小化JSON响应消耗的带宽量。 我似乎无法找到将视图转换为简单数组的方法。有什么建议吗?

感谢。

1 个答案:

答案 0 :(得分:19)

您可以使用_show and _list函数,它们可以分别获取文档或视图,并可以以您需要的任何格式发送转换后的响应。 (在这种情况下,JSON)

更新:我使用您在我自己的CouchDB上提供的数据运行了一个简单的测试。这是我最后编写的列表函数。自定义它以满足您的需求。 :)

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