saravanakumar
saravanakumar

Reputation: 1777

Add hyphen symbol in json object creation in javascript

When I am trying to add hyphen to json creation it shows error as;

SyntaxError: missing : after property id
student-ids : [{

My JSON is like this:

var testJson = {
student-ids : [{
student-id : "123"},{
student-id : "21321"},{
student-id : "123"},{
student-id : "21321"
}]
};
console.log(testJson)

Upvotes: 0

Views: 347

Answers (2)

ManMohan Vyas
ManMohan Vyas

Reputation: 4062

var testJson = {
   "student-ids" : [{
   "student-id" : "123"},{
"student-id" : "21321"},{
"student-id" : "123"},{
"student-id" : "21321"
}]
};
console.log(testJson)

Upvotes: 1

Blender
Blender

Reputation: 298156

Quote the property names that contain dashes:

"student-id" : "123"

You may want to use an underscore instead:

student_id : "123"

Or camel case:

studentId : "123"

Otherwise, you'll have to access the property with the bracket notation foo['student-id'], which doesn't look as nice as foo.studentId.

Upvotes: 2

Related Questions