L0n3Prospector L0n3Prospector - 1 year ago 105
JSON Question

Can you have a space in the object name in JSON string and still retrieve it?

I have a JSON object which appears as such:

$leo = {"Leonardo DiCaprio":{"ht":"70","wt":"222","eyes":"blue","movie":"titanic"}

But I am having a hard time accessing the data. I have tried:

var json = JSON.parse($leo);
alert(json.'Leonardo DiCaprio'['movie']);


var json = JSON.parse($leo);
alert(json.['Leonardo DiCaprio']['movie']);


var json = JSON.parse($leo);
var name = 'Leonardo DiCaprio';

None have worked for me. But when I remove the space and do alert(json.LeonardoDiCaprio['movie']; I get the movie.

Is there any way to retrieve the data and keep the space?

Answer Source

The foo.bar and foo['bar'] syntax are mutually exclusive but behave the same, in most cases. foo.['bar'] is not valid.

This is described in the spec at section 12.3.2:

Properties are accessed by name, using either the dot notation:

MemberExpression . IdentifierName
CallExpression . IdentifierName

or the bracket notation:

MemberExpression [ Expression ]
CallExpression [ Expression ]

The IdentifierName used in the dot notation must not contain whitespace (section 11.6), so you must use the bracket notation in that case.

The exact rules for which Unicode characters are legal are defined in Unicode TR#31 and specified in section 2.

All you need to do here is json['Leonardo DiCaprio'] and you'll fetch the inner object.