If you are trusting,
you might go ahead and evaluate the content as before and create data structures
corresponding to the JSON response:
var responseObject = eval(xhr.responseText);
152 Par t I : C o r e I d e a s
If you are creating the data to be evaluated, this is most likely safe. If the user is creating
it and you are mirroring it back, this is very unsafe. You will see this problem very clearly in
Chapter 7.
Regardless of the specific problem, given the mischief some Internet users make, it is
a bit too trusting to go with a direct evaluation. It is far safer to look at the data a bit first
before using it. To do this, include the JavaScript JSON library mentioned earlier available
at http://json.org:
Next, use the parseJSON() method to look to see if the packet looks correct. This really
adds no major amount of security since it just looks to see if the format looks correct and
unexpected characters are not encountered; if ???these conditions are met??? or ???so???, it does an
eval() as we saw before.
var jsonObject = xhr.responseText.parseJSON();
var rating = jsonObject.rating;
var total = jsonObject.votes;
var average = jsonObject.average;
However it is a step in the right direction and more ideas that will improve the format
such as wrapped JSON will be presented in Chapter 7.
Pages:
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233