40

I am having trouble with JSON returned from a web service. It looks like the JSON lacks quotes, but when I add quotes to the JSON, I get an error. Here is the error message: 'Uncaught SyntaxError: Unexpected token o. When I log the string to console:[object Object],[object Object]

Here is some example code that simulates the error:

//Error I am trying to solve
var jsonString = '[{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}]';
var myData = JSON.parse(jsonString);

$(document).ready(function() {
    var $grouplist = $('#groups');
    $.each(myData, function() {
        $('<li>' + this.Name + '</li>').appendTo($grouplist);
    });
});

Here is the same code with the single quotes around the string. It works

//Successful Javascript
var jsonString = '[{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}]';
var myData = JSON.parse(jsonString);

$(document).ready(function() {
    var $grouplist = $('#groups');
    $.each(myData, function() {
        $('<li>' + this.Name + '</li>').appendTo($grouplist);
    });
});

//Successful HTML
<ul id="groups"></ul>

But when I try to add quotes to the string, like I seem to need to in my real code, it fails:

//Does not work when I need to append quotes to the string:
var jsonStringNoQuotes = [{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}];
jsonStringQuotes = "'" + jsonStringNoQuotes + "'";
var myData = JSON.parse(jsonStringQuotes);

$(document).ready(function() {
    var $grouplist = $('#groups');
    $.each(myData, function() {
        $('<li>' + this.Name + ',' +  this.Id + '</li>').appendTo($grouplist);
    });
});

Here is the error: log string to console:[object Object],[object Object] data.js:809 Uncaught SyntaxError: Unexpected token '

I'm stumped. Any help appreciated! Thank you!

4 Answers4

67

Without single quotes around it, you are creating an array with two objects inside of it. This is JavaScript's own syntax. When you add the quotes, that object (array+2 objects) is now a string. You can use JSON.parse to convert a string into a JavaScript object. You cannot use JSON.parse to convert a JavaScript object into a JavaScript object.

//String - you can use JSON.parse on it
var jsonStringNoQuotes = '[{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}]';

//Already a javascript object - you cannot use JSON.parse on it
var jsonStringNoQuotes = [{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}];

Furthermore, your last example fails because you are adding literal single quote characters to the JSON string. This is illegal. JSON specification states that only double quotes are allowed. If you were to console.log the following...

console.log("'"+[{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}]+"'");
//Logs:
'[object Object],[object Object]'

You would see that it returns the string representation of the array, which gets converted to a comma separated list, and each list item would be the string representation of an object, which is [object Object]. Remember, associative arrays in javascript are simply objects with each key/value pair being a property/value.

Why does this happen? Because you are starting with a string "'", then you are trying to append the array to it, which requests the string representation of it, then you are appending another string "'".

Please do not confuse JSON with Javascript, as they are entirely different things. JSON is a data format that is humanly readable, and was intended to match the syntax used when creating javascript objects. JSON is a string. Javascript objects are not, and therefor when declared in code are not surrounded in quotes.

See this fiddle: http://jsfiddle.net/NrnK5/

flagoworld
  • 3,196
  • 2
  • 20
  • 16
2
var jsonStringNoQuotes = [{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}];

it will create json object. no need to parse.

jsonStringQuotes = "'" + jsonStringNoQuotes + "'";

will return '[object]'

thats why it(below) is causing error

var myData = JSON.parse(jsonStringQuotes);
Pankaj Sharma
  • 1,833
  • 1
  • 17
  • 22
  • 1
    I don't think wrapping array into single quotes will give you a string literal of that array. It will rather give you something like `'[object], [object]'` which obviously makes no sense to parse. Use `JSON.stringify`. – volpav Oct 08 '13 at 04:54
  • thats what i am saying.. please read my answer again – Pankaj Sharma Oct 08 '13 at 05:09
  • Sorry, I missed "no" in "no need to parse" (early morning here). You should probably correct the `'[object]'` output though as this is not how this particular array is represented (sorry for being pedantic but it will just make it easier for people to understand your solution if what you write is actually what they can discover themselves). – volpav Oct 08 '13 at 05:25
1

Your last example is invalid JSON. Single quotes are not allowed in JSON except inside strings. In the second example, the single quotes are not in the string, but serve to show the start and end.

See http://www.json.org/ for the specifications.

Should add: Why do you think this: "like I seem to need to in my real code"? Then maybe we can help you come up with the solution.

1

Maybe what comes from the server is already evaluated as JSON object? For example, using jQuery get method:

$.get('/service', function(data) {  
  var obj = data;

      /* 
         "obj" is evaluated at this point if server responded 
         with "application/json" or similar.
       */
      for (var i = 0; i < obj.length; i++) {
        console.log(obj[i].Name);
      }
    });

Alternatively, if you need to turn JSON object into JSON string literal, you can use JSON.stringify:

var json = [{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}];
var jsonString = JSON.stringify(json);

But in this case I don't understand why you can't just take the json variable and refer to it instead of stringifying and parsing.

volpav
  • 5,090
  • 19
  • 27
  • @user3754676 Your JSON might not be valid (for example, missing double quotes). You can check it using http://jsonlint.com – volpav Jul 06 '15 at 02:44