Access Hyphenated JSON Elements Using Javascript
April 21, 2009 8:12 PM   Subscribe

How to parse JSON elements with hyphens with javascript?

I am trying to embed tumblr posts to an existing website. Their API includes a JSON response to be used for javascript. However, when trying to access elements with hyphens (i.e. tumblr_api_read.posts[0].photo-caption), Javascript parses the hyphen as a minus, and returns NaN as the result.

How do I access the hyphenated elements, or escape the "-"?

Thanks in advance!
posted by theRussian to Technology (3 answers total) 2 users marked this as a favorite
Best answer: Objects are essentially hash tables in Javascript (see the Objects section here); you can access the property with tumblr_api_read.posts[0]["photo-caption"].
posted by enn at 8:25 PM on April 21, 2009

In Javascript,

is the same thing as


You can use the latter form to access properties whose names are not themselves valid Javascript variable names.
posted by gsteff at 8:36 PM on April 21, 2009

Response by poster: Thanks enn! That did it, I kept trying various versions of tumblr_api_read.posts[0]."photo-caption", tumblr_api_read.posts[0].["photo-caption"], etc. Didn't think to exclude the .
posted by theRussian at 9:35 PM on April 21, 2009

« Older Groomsmen Gifts for the Non Brahs Out There?   |   Portugal Summer Travel tips please Newer »
This thread is closed to new comments.