views:

1808

answers:

4

I'm experiencing an error that I haven't been able to find any mention of anywhere. I'm developing an AJAX-enabled WCF web service with ASP.NET. In my ASP.NET master page's , I included the json.js file, copied fresh from json.org. When I run the page, it fails (VS 2008 catches a Javascript exception) on the first line of code in json.js (following lots of comments), which is:

JSON = JSON || {};

The error says that JSON is undefined:

Microsoft JScript runtime error: 'JSON' is undefined

Well, duh! That's why the line is testing if it's defined and if so setting it to an empty object! It is supposed to be undefined, right? Last I heard it was not an error in Javascript to perform such an operation on an undefined variable.

Can anyone give me a clue as to what's going on here? I suspect it's something gone wrong elsewhere that's somehow causing this problem. I don't have deep experience with either Javascript or ASP.NET so it might be that I'm missing some common gotcha in the setup.

+4  A: 

You should be using json2.js. The offending line has been changed:

// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.

if (!this.JSON) {
    this.JSON = {};
}
Kinopiko
Excellent, this did the trick! Thanks. Out of curiosity, what does the this keyword do in a global context like this?
Nate C-K
`this` is the global scope, i.e. `this === window`.
Matthew Crumley
Nate C-K, if this solves your problem, please "accept" the answer. You can undo that later on if you like. It will give you points and also help next time you ask a question.
Kinopiko
A: 

As mentioned, you should be using json2.

The error, however, stems from MS handling of global variables. Try window.JSON = window.JSON || {}; From then on, JSON should work just fine.

John Smith
Ain't no MS thing, just a JavaScript thing.
Crescent Fresh
+1  A: 

you might have to do var JSON = JSON || {}; I have run in to similar problems with Javascript in IE8.

fredrik
That's another point I'd forgotten to mention, our sysadmins just upgraded us to IE8 yesterday. I wonder what other surprises are in store.
Nate C-K
A: 

I have the same error and i was already using json2;

for me work when i add var

var JSON = JSON || {};

Davinho