Search code examples
javascriptjsonbackbone.js

"Uncaught SyntaxError: Unexpected token" with JSON parse in backbone


I have a Rails/backbone app I'm working on. I'd like to convert one of the attributes coming from Rails to a javascript array in backbone.

Rails is delivering the attribute as stringified JSON (I think)

$(function () {
  App.initialize({ projectsJson: [{"skill":"[\"Beginner\",\"Advanced\"]"}] });
});

Then trying to convert it in backbone:

App.Models.Project = Backbone.Model.extend({

  initialize: function() {
    this.set({
      skill: JSON.parse(this.get('skill'))
    });
  }

I get this error: Uncaught SyntaxError: Unexpected token B

I've tried inspecting the attribute in devtools:

var test = this.get('skill');

Which shows: "["Beginner","Advanced"]"

and:

var test = JSON.parse(this.get('skill'));

Which shows an array object with 2 elements.

If I make a new attribute:

this.set({
  skillTEST: JSON.parse(this.get('skill'))
});

I can then use this new attribute and it works fine as an array. I'm very confused. Why can't I change the original attribute?

Is there a better way to do this? All I really want is that string coming from rails to be an array in backbone.

UPDATE:

I took a new approach based on meagar's answer. I decided to just not pass the array around as JSON.

the code:

JSON.stringify(new Array("Beginner","Advanced"));

produces: "["Beginner","Advanced"]"

backbones collection.create method is sending a POST request with:

{"skill":"[\"Beginner\",\"Advanced\"]"}

And I could not figure out how to fix that so I stopped using JSON.stringify.


Solution

  • The string "\"Beginner\",\"Advanced\"]" is not valid JSON, so no, it will not parse.

    You either need to stop using JSON (it's really not apparent why you are here) or use a correctly formatted JSON string.

    In the first case, you would simply pass around JavaScript arrays, and specify your configuration with an array literal:

    App.initialize({ projects: [{skill: ['Beginner', 'Advanced']}] });
    

    In the second case, you need to produce a valid JSON string in order to parse it:

    App.initialize({ projectsJson: [{skill: '["Beginner","Advanced"]'}] });
    

    In either case, you can make things far easier on yourself by choosing the correct quotes so that you don't need to escape your internal quotes, and by not needlessly wrapping your object literal keys in quotes.