Andrew
Andrew

Reputation: 3989

Getting 'Uncaught SyntaxError: Unexpected token o in <unknown file>:1' when using JSON.parse

I'm setting a variable to be equal to JSON text like so:

var httpResponseBackup = {"findItemsByKeywordsResponse":[{"searchResult":["nada"]}]}

However, when I run my cloud code, it gives me this error:

Uncaught SyntaxError: Unexpected token o in <unknown file>:1

Based on what I've found by googling this error, it has to do with the following line of code:

var ebayResponse = JSON.parse(httpResponseBackup);

Am I formatting the JSON text in httpResponseBackup incorrectly?

Upvotes: 2

Views: 665

Answers (2)

S McCrohan
S McCrohan

Reputation: 6693

Given:

var httpResponseBackup = {"findItemsByKeywordsResponse":[{"searchResult":["nada"]}]};

var httpResponseBackupString = '{"findItemsByKeywordsResponse":[{"searchResult":["nada"]}]}';

Then:

JSON.stringify(httpResponseBackup) == httpResponseBackupString

And:

JSON.parse(httpResponseBackupString) will return a new object with the same structure as httpResponseBackup.

Upvotes: 1

Transcendence
Transcendence

Reputation: 2696

JSON.parse expects a string, stringified JSON. You are passing in something that's already a JSON object. Therefore you can set your response to the object:

var ebayResponse = httpResponseBackup;

Alternatively you could set your httpReponseBackup to the string value:

var httpResponseBackup = '{"findItemsByKeywordsResponse":[{"searchResult":["nada"]}]}'

docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

Upvotes: 6

Related Questions