Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialA X
12,842 PointsHow does the parse function in JSON "know" where to parse?
I just watched Dave's video on Parsing in JSON. His example code is:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
var employees = JSON.parse(xhr.responseText);}
};
xhr.open('GET', 'data/employees.json');
xhr.send();
What I'm not understanding is how does the parse function "know" where/how to parse the contents of the long JSON string or whatever its original format is? How do we know that JSON.parse is parsing in the manner we want?
1 Answer
Steven Parker
231,269 PointsThe parse function follows the structure of the JSON string.
The structure is represented by braces, brackets, commas, and colons embedded in the string. The parse function simply looks for these and translates the structure indicated by them into a normal JavaScript object.
We know the function has operated correctly if it completes without error. It throws a SyntaxError exception if it does not recognize a valid JSON format.