First time working with javascript and JSON. Curious why this causes a comiler error:
var dataTypes = new function() {
this.list = "list"; this.boolean = "boolean";
};
var jsonDataTypes = [
{dataTypes.list:"Food For Lunch"}
];
When this doesn’t.
var dataTypes = new function() {
this.list = "list"; this.boolean = "boolean";
};
var jsonDataTypes = [
{"Food For Lunch":dataTypes.list}
];
Why am I allowed to use a variable for the value but not for the key?
The error is:
Multiple markers at this line
- Missing semicolon
- Syntax error on token(s), misplaced
construct(s)
- Missing semicolon
- Syntax error on tokens, delete these
tokens
First, you are working with JavaScript objects, not JSON. Objects are a data type in JavaScript, whereas JSON is a data transfer format.
The keys inside object literals must be valid identifiers, strings or numbers, because keys are interpreted literally. Identifiers are not allowed to have dots (
.) and certain other characters in it. See the specification for more information.As you want to use the value of
dataTypes.listas key, you have to create the object in two steps:or if you want to use it literally, use a string: