-1

I'm a beginner in Javascript and I have a little problem with the eval() function. So, first I get some data through an API :

const xhr = new XMLHttpRequest();
xhr.open('GET', url, false);
xhr.send(null);

So, at that point, I know that xhr.response is for example :

"{"data":[{"id":41462,"created_at":"2017-11-13 [...]}"

Now, I want to make a dictionary with it, so I do :

var req = eval(xhr.response);

But the console shows me "Uncaught SyntaxError: Unexpected token : at window.onload" at the eval() step. And I don't know really why... any tips ?

3
  • 3
    Use JSON.parse() instead of eval() Commented Nov 13, 2017 at 17:02
  • that looks like JSON instead of doing eval do JSON.parse(xhr.response) it will work Commented Nov 13, 2017 at 17:02
  • Me thinks your JSON isn't valid. Commented Nov 13, 2017 at 17:05

1 Answer 1

2

eval expects to be passed a chunk of JavaScript. A JSON representation of an object is not (by itself) valid JavaScript.

To parse JSON, use JSON.parse and not eval.

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

5 Comments

Surely any valid JSON will also be parsed as valid JS? Not trying to be contrarian, but do you have an example of valid JSON, but not valid JS?
@evolutionxbox not always. stackoverflow.com/questions/23752156/…
@Amy good to know. A̶l̶t̶h̶o̶u̶g̶h̶ ̶I̶ ̶d̶o̶n̶'̶t̶ ̶t̶h̶i̶n̶k̶ ̶i̶t̶ ̶s̶a̶t̶i̶s̶f̶i̶e̶s̶ ̶O̶P̶'̶s̶ ̶e̶r̶r̶o̶r̶.̶ Nevermind... it does.
Thank's a lot! I didn't know about JSON, you're helpful :)
@Quentin ooooo. Interesting

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.