-1

I'm doing a pretty basic Backbonejs model.save:

this.model.save(null, {
    success: function(model, response)
    {

    },

    error: function(model, response)
    {

    }
});

The model contains some string attributes, and an array of objects. When I look at the raw ajax request that Backbone makes (using jQuery ajax, I believe), it wraps the array in double quotes. This causes my endpoint to try to parse the value as a string, rather than an array:

{
    id: 108,
    name: "My model",
    questions: "[{"id": 100, "name": "question 1"}, {"id": 101, "name": "question 2"}]"
}

Has anyone encountered this before? Is there a way to force Backbone/jQuery to not wrap the array in quotes, i.e.:

questions: [{"id": 100, "name": "question 1"}, {"id": 101, "name": "question 2"}]

Update, backbone's sync function calls JSON.stringify on the output of model.toJSON, and JSON.stringify is what is adding those quotes. For example:

console.log(JSON.stringify({name: 'test1', animals: ['horse', 'pig']}));

Outputs:

{"name":"test1","animals":"[\"horse\", \"pig\"]"}
Clayton
  • 6,089
  • 10
  • 44
  • 47
  • What is your `model.toJSON()`? – Jordan Eldredge Jul 13 '16 at 19:34
  • It does NOT contain the quotes – Clayton Jul 13 '16 at 21:12
  • You could try setting a breakpoint (or typing `debugger;`) here: https://github.com/jashkenas/backbone/blob/master/backbone.js#L1407 I'm guessing if you stepped through that code, you might find where it's happening. – Jordan Eldredge Jul 14 '16 at 00:00
  • That is not even a valid string and this is not likely to happen. Please share a [mcve] reproducing the issue. – T J Jul 14 '16 at 05:15
  • @TJ right, but that is exactly what backbone is hitting my endpoint with, hence the issue – Clayton Jul 14 '16 at 20:35
  • @Clayton Well like I said, backbone was **not** causing the issue. No one could find an answer without an MCVE since you didn't even tag the question with prototype. – T J Jul 15 '16 at 04:26

1 Answers1

0

We are using an old version of prototype.js, v.1.6.0.3, which was causing this issue. Adding the following resolved it:

if(window.Prototype) 
{
    // Disable prototype's buggy version of toJSON for arrays
    delete Array.prototype.toJSON;
}

Credit to: https://stackoverflow.com/a/20331694/1449 and: JSON.stringify() array bizarreness with Prototype.js

Community
  • 1
  • 1
Clayton
  • 6,089
  • 10
  • 44
  • 47