Unit 6 · JavaScript in the page
Why JSON.parse, not eval, reads JSON
eval runs any code in the text it is given, so text from a server or a user can take over your page. JSON.parse only reads data and fails safely on anything else.
The mix-up
What people often think
“eval is a fine way to read JSON.”
What the tutor says
eval runs whatever code is in the text, which is a security hole. JSON.parse only reads data.
How it works
If JSON.parse rejects some text, the text is not valid JSON. Fix the text, usually quotes or a trailing comma, rather than reaching for a function that will happily run whatever is inside.
Close cousins of this mix-up
The tutor watches for these in the same lesson.
“eval can read it, so use eval.”
eval runs any code hidden in the text. Make the text valid JSON and use JSON.parse.
Practise it with a tutor watching
JSON
Turn JSON text into objects and back, and spot JSON that will not parse.
Free with an account. The first two units need no account.