1

Comments aren't allowed in JSON files (as seen in this answer). So, my question is if comments are allowed in javascript object declaration (in JSON like notation).

Example:

var myObject = {
    prop1: 'value1', // prop1 description
    prop2: 'value2' /* prop2 description */
}

Is this guaranteed to work or its browser dependent?

Community
  • 1
  • 1
sergioFC
  • 5,926
  • 3
  • 40
  • 54
  • 4
    This is just javascript, of course comments are allowed. – dfsq Nov 01 '14 at 12:30
  • Although this not json this object declaration with comments is allowed. `JSON.stringify(myObject)` will create valid json without problems. – Barry Nov 01 '14 at 12:30
  • 2
    It's not guaranteed to work because of the trailing comma, but that has nothing to do with the comments. – JJJ Nov 01 '14 at 12:34
  • Thanks @Juhana yep, what a mistake, trailing comma won't work in IE, edited. – sergioFC Nov 01 '14 at 12:38
  • Tanks @dfsq, as you have made the first comment arguing its only javascript, provide it if you want as an answer and I'll accept it. – sergioFC Nov 01 '14 at 12:40
  • 1
    There is no such thing as JavaScript which is in JSON-like notation. It is JSON that is JavaScript-like. – JAAulde Nov 01 '14 at 12:54

1 Answers1

5

This is just normal usage of comments in javascript program, nothing special about it. You can use single or multi-line comments the way you usually would use:

var myObject = {
    prop1: 'value1', // prop1 description
    prop2: 'value2', /* prop2 description */
    prop3: /* or even so */ 'value3'
}

Also you should not confuse javascript object notation with JSON. Above is not JSON (and as you correctly stated comments are not allowed within JSON body), JSON is just a string representation of the javascript object.

dfsq
  • 191,768
  • 25
  • 236
  • 258