41

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!

6
  • jaon PARSE take string as parameter Commented Oct 8, 2013 at 4:43
  • These code snippets certainly produce an error, but I think you're looking at the wrong thing. Can you post the code that retrieves the JSON string from the server? Commented Oct 8, 2013 at 4:47
  • Your first code example doesn't simulate the issue. Which one specifically are you asking about. Your last one is definitely incorrect. Commented Oct 8, 2013 at 4:47
  • You need to post some actual data and code. Commented Oct 8, 2013 at 4:52
  • Add the json2.js your file and try.This solved the same problem for me. Commented Oct 8, 2013 at 5:31

4 Answers 4

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/

Sign up to request clarification or add additional context in comments.

4 Comments

I've been working on this same problem for hours. Thanks for the information.
I had a rough time adding the single quotes to my JSON string because it was in a data attribute. I solved it by doing a JSON.stringify before doing a JSON.parse.
Same as people here, I wasted an hour wandering around there and then finally found this simple, clear explanation, thank you!
thanks a lot, I was also facing same problem. solved now
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);

3 Comments

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.
thats what i am saying.. please read my answer again
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).
2

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.

1 Comment

@user3754676 Your JSON might not be valid (for example, missing double quotes). You can check it using jsonlint.com
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.