Accessing Values in Javascript JSON Objects with Keys containing Hyphens (Dashes)

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

Craig Lotter is an established web developer and application programmer, with strong creative urges (which keep bursting out at the most inopportune moments) and a seemingly insatiable need to love all things animated. Living in the beautiful coastal town of Gordon's Bay in South Africa, he games, develops, takes in animated fare, trains under the Funakoshi karate style and for the most part, simply enjoys life with his amazing wife and daughter. Oh, and he draws ever now and then too.
This entry was posted in Technology & Code, Tutorials and tagged , , , , , . Bookmark the permalink.