kate_hudson kate_hudson - 10 months ago 78
Javascript Question

Access JSON Object data with space in name

I make an API call and get returned some JSON. I then parse this JSON using

var json = $.parseJSON(result);

To get to the level I need to within this json object, I do something like this


That will print something like the following to the console

Option "1166325"
Option Two "3329076"

So if I do


I am printed out 1166325. If however I do

console.log(json.data[0].value.Option Two)

I get an error SyntaxError: missing ) after argument list. I have also tried

console.log(json.data[0].value.['Option Two'])

But this returns SyntaxError: missing name after . operator

So how can I access this data considering there is a space in the name?


Answer Source

Yes, just lose the . character:

console.log(json.data[0].value['Option Two'])

This is known as bracket notation and can always be used to access a property. Dot notation can only be used when the property name is a valid Javascript identifier. This means (a) letters and numbers; (b) _ underscores; (c) $ dollar signs.