Im looking at another developers code that parses some JSON. I cant really see how it works or if its a good idea…
hmlPlaylist.prototype.loadVideos_callback = function (data) {
var jsonData = '';
var jsonError = false;
try {
jsonData = eval("(" + data + ")");
} catch (jError) {
jsonError = true;
}
if (!jsonError) {
if (jsonData.playlists.length > 0) {
this.buildPlaylistList(jsonData.playlists);
}
if (jsonData.videos.length > 0) {
this.buildVideoList(jsonData.videos);
this.bindVideoNavs();
}
}
else {
// no json returned, don't do anything
}
};
Its the line
jsonData = eval("(" + data + ")");
That gets me. What does this do to the data? I thought you had to use an extarnal class library to parse JSON data?
I can see later on that he iterates the collection like this:
for (var i = 0; i < playlistCount; i++) {
var p = playlists[i];
So is this really a good way of going through JSON?
Most modern browsers support a native
JSON.parsemethod that does exactly this. If you are targeting a browser that does not, you can use Douglas Crockford’s implementation provided here (scroll to the bottom).In any case, do not use
evalif you can at all avoid it.Update (regarding
eval):As JSON.org states:
What does this mean in practice? Well, it means that any valid JSON object is also valid JS code (in technical terms: it’s a valid JS expression that evaluates to an object literal). Therefore, you can paste JSON into a file and tell e.g. your browser to load it as JavaScript and it will do so without any error or warning (of course the “JavaScript” won’t actually do anything because it’s just the representation of an object and not procedural code).
Since we established that JSON can be interpreted as JavaScript, it can also be passed to
eval. Let’s see what the MDC has to say abouteval:The above is perhaps not the best explanation, but it does say what happens: JSON can be seen as a JS expression.
evaltakes a string representing a JS expression (in this case, a string containing JSON), evaluates it, and returns the result. It’s like a mini-compiler that you can feed code to at runtime, and it will run the code for you and return the result. In this case, the result will be a JS object (as already mentioned, JSON is a valid JS expression that represents an object).So if you have
Then
object1andobject2will be two different but identical objects.