主干js,JSON字符串存储不正确

backbone js, JSON string is not stored properly

本文关键字:存储 不正确 字符串 JSON js 主干      更新时间:2023-09-26

以下是完整的代码:

var picTempJSON = JSON.stringify(pictures);
//code to update model
usersCollection.fetch({
  success : function() {
    var getModel = usersCollection.where(checkFBAccountIdJSON);
      //console.log(PersonJson);
    for (var i in getModel) {
      getModel[i].set('pictures', picTempJSON);
      getModel[i].save();
    }
    console.log(usersCollection.toJSON());
  },
  error : function() {
      // something is wrong..
  }
}); 

输入字符串:

["xxxx.jpg","xxxx.jpg","xxxxx.jpg"]

输出字符串:

pictures = "['"xxxx.jpg'",'"xxxx_n.jpg'",'"xxxxx.jpg'"]";

我遇到的问题是,输入字符串没有反映输出字符串(或存储在模型中的字符串),当我必须将字符串重新转换为JSON对象时,这将导致以后出现问题,因为它是无效的JSON,原因是反斜杠

如果您真的必须将其作为字符串存储在模型中,您可以调用

var pictures = JSON.parse(model.get('pictures'));

获取数据或重写模型的toJSON方法并在其中调用JSON.parse(...),因此在迭代收集时,每个模型都将准备好所有

var AnyModel = Backbone.Model.extend({
  //...
  toJSON: function() {
    return {
       //...
       'pictures': JSON.parse(this.get('pictures'))
       //...
    }
  }
  //...
});