Search code examples
javascriptjsonto-json

Getting an error on JSON.parse


I was reading an article by Derick Bailey Don’t Return A JSON Document From The toJSON Method

I was trying to convert the following JSON object into Javascript:

var userJSON = "{\"firstName\":\"Derick\",\"lastName\":\"Bailey\"}";
var parseOnce = JSON.parse(userJSON.to_json).first;
var userObject = JSON.parse(parseOnce.to_json).first;

When I run the code I get a "SyntaxError: Unexpected token u"

Here is a jsbin of the same code https://jsbin.com/zugojoyaro/edit?js,console


Solution

  • this is a copy & paste problem from the blog post... (and a small error in the blog post, itself)

    
    var userJSON = "{\"firstName\":\"Derick\",\"lastName\":\"Bailey\"}";
    
    var parseOnce = JSON.parse(userJSON);
    

    this works... but the code you have:

    var parseOnce = JSON.parse(userJSON.to_json).first;

    includes a .to_json and a .first attribute that don't exist. it looks like your trying to use ruby code on a JavaScript object