L0n3Prospector
L0n3Prospector

Reputation: 27

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']);

and

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

and

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

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?

Upvotes: 2

Views: 347

Answers (2)

Amit
Amit

Reputation: 1121

You are missing the ending "}" in the JSON String $leo.

-Amit

Upvotes: 1

ssube
ssube

Reputation: 48287

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.

Upvotes: 3

Related Questions