JavaScript AJAX Basics (retiring) Programming AJAX Parsing JSON Data

How 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
Steven Parker
173,537 Points

:point_right: The 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.