Accessing Values in Javascript JSON Objects with Keys containing Hyphens (Dashes) CodeUnit 12 AUG 2010

In Javascript, JSON objects (well, JS objects in general) have a great short hand little way of accessing values using the fullstop object notation.

In other words, using a JSON dataset looking like:

{“status”:”1″,”message-data”:”Success!”}

we could access the “status” value by simply entering:

alert(myobject.status);

However, if we tried the same thing with the “message-data” key, you will note that this will fall over syntactically straight away – all because of that silly hyphen (dash).

So the way around this?

Well you basically have to revert to the long notation format to get at the data associated with these keys, meaning that you would now need to do something like this:

alert(myobject[“message-data”]);

And now you know.

Nifty.

Related Posts:

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.