0

Anyone can probably figure this out. Why does the following JSON object cause a JSON.parse error? It appears to be a valid JSON object. I'm sure I'm doing something completely idiotic in this, the 14th hour of this long workday.

var t = {
    "message": "ok, Heru we go!"
};

JSON.parse(t);

--> syntaxError: Unexpected token o

Many thank yous!

UPDATE

This is the kind of question you ask when you have 2 new puppies and are trying to code on 3 hours of sleep. Please let this serve as a warning for those of you who have come here looking for the same answer- Go to sleep. Give it up. You're worthless today. Try again tomorrow.

1
  • "[object Object]" is not valid JSON... Commented Jul 8, 2013 at 22:49

4 Answers 4

8

JSON.parse expects a string. The value of t is a javascript object, so it doesn't need to be parsed.

If you had:

var t = "{\"message\":\"ok, Heru we go!\"}";

then JSON.parse would be what you were after.

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

3 Comments

OH MY LORD I AM AN IDIOT! PLEASE SOMEONE TELL ME TO GO TO SLEEP AND TRY AGAIN IN THE MORNING.
Don't worry, happens to all of us. :)
@Hairgami_Master I have done way worse. Happens. Good night ^^
4

Don't you want JSON.stringify(t);?

JSON.parse(s); is used to get the object out of a string.

JSON.stringify(t); is used to convert your JSON object to its string equivalent.

1 Comment

YES YES! I can't believe I'm doing this- can you tell I have two new puppies in my house and am getting absolutely no sleep?
2

t is already a JavaScript object. JSON.parse only works on strings. You could do JSON.parse(JSON.stringify(t)), but that would be kind of pointless.

1 Comment

Thank you! I'm beyond sleep deprived and can't believe I even posted this question. I will not try and delete it as a warning to those of us who try and program on little to no sleep.
0

The JSON here should be a string. You are passing an object as parameter. Try this

JSON.parse('{ "message": "ok, Heru we go!" }');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.