【问题标题】:Backbone JS parse json attribute to a collection's modelBackbone JS 将 json 属性解析为集合的模型
【发布时间】:2012-12-30 07:44:17
【问题描述】:

我无法将 json 解析为模型。

这是 JSON:

[
{
    "name": "Douglas Crockford",
    "email": "example@gmail.com",
    "_id": "50f5f5d4014e045f000002",
    "__v": 0,
    "items": [
        {
            "cena1": "Cena1",
            "cena2": "Cena2",
            "cena3": Cena3,
            "cena4": "Cena4",
            "cena5": "Cena5",
            "cena6": Cena6,
            "_id": "50ee3e782a3d30fe020001"
        }
    ]
}

]

我需要一个模型来拥有这样的“项目”属性:

cena = new Model({ 
           cena1: "Cena1", 
           cena2: "Cena2",
           ... 
});

我尝试过的:

var cenaCollection = new Backbone.Collection.extend({
   model: Cenas,
   url: '/orders',

   parse: function (response) {
      return this.model = response.items;
   }

});

然后我创建集合的新实例并获取,但我得到“response.items”总是“未定义”:|

提前致谢!

【问题讨论】:

    标签: json parsing backbone.js collections


    【解决方案1】:

    parse 函数应返回要在模型上设置的属性哈希(请参阅documentation here)。所以你只需要:

    parse: function (response) {
       return response[0].items;
    }
    

    【讨论】:

    • @asirgado 我刚刚注意到您的 JSON 似乎被包裹在一个数组中——对吗?如果是这样,您将需要 response[0].items ...?
    • 刚刚尝试过,它可以按我的需要工作!谢谢!!如果我在数组中获得更多“项目”,它会起作用吗?谢谢!
    猜你喜欢
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-29
    相关资源
    最近更新 更多