question about valid keys in JSON

M

Morgan Packard

var Functions = {
myfunction : function() { }

}

var refToFunction = Functions.myfunction;

var myJsonObj1 = {
refToFunction : "some value"
}


var myJsonObj2 = {
Functions.myfunction: "some value"
}


Can anyone explain why my browser complains when creating the second
myJsonObj2 (missing : after property id
[Break on this error] Functions.myfunction : "some value" \n)? Can I
not have dot notation in a JSON key?

thanks,

-Morgan
 
H

Henry

var Functions = {
myfunction : function() { }

}

var refToFunction = Functions.myfunction;

var myJsonObj1 = {
refToFunction : "some value"

}

var myJsonObj2 = {
Functions.myfunction: "some value"

}

Can anyone explain why my browser complains when creating
the second myJsonObj2 ...
<snip>

The property names used in an object literal may only be Identifiers,
string literals or numeric literals (and numeric literals don't work
in some implementations (e.g. on Mac IE 5)).
? Can I not have dot notation in a JSON key?

A property accessor is none of an Identifier, a string literal or a
numeric literal, so no you cannot. But if you want a dot in the
property name use a string literal; - {"Functions.myfunction": "some
value"} - is a legal object literal. Indeed, strictly JSON requires
the property names used to be quoted else what you have is just a
javascript object literal and not JSON at all.
 
L

Lasse Reichstein Nielsen

....
var myJsonObj2 = {
Functions.myfunction: "some value"
}


Can anyone explain why my browser complains when creating the second
myJsonObj2 (missing : after property id
[Break on this error] Functions.myfunction : "some value" \n)? Can I
not have dot notation in a JSON key?

Indeed, you cannot have a dot.

In fact, in JSON all keys *must* be quoted. I.e.:
{"refToFunction" : "some value", "Functions.myfunction": "some value"}
Many parsers for JSON will ignore this constraint, especially those using
Javascript's "eval" function.

In Javascript, keys that are also valid identifiers or number literals
may be left unquoted:
{refToFunction: "some value", "Functions.myfunction": "some value",
2: "some value", true: "some value"}

/L
 
D

dhtml

Morgan said:
var Functions = {
myfunction : function() { }

}

In addition to the information you already got, JSON doesn't allow
function expressions for values.

JSON uses a subset of Object Literal Notation. For more details, please
see: http://www.json.org/

Garrett
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,571
Members
45,045
Latest member
DRCM

Latest Threads

Top