admin管理员组

文章数量:1389863

It seems there are different standards out there on labels for JSON, some want quotes around JSON object labels, some do not. Can someone tell me what the standard is?

Quotes are bad camp

Chrome

{"label":1111} - SyntaxError: Unexpected token :

{label:1111} - Works

Firefox

{"label":1111} - SyntaxError: invalid label

{label:1111} - Works

Quotes are good camp

JSLint

{"video_id":1111} - JSON: good.

{video_id:1111} - JSON: bad. Expected a string and instead saw 'video_id'

PHP

echo json_encode(array('label' => 1111));
{"label":1111}

It seems there are different standards out there on labels for JSON, some want quotes around JSON object labels, some do not. Can someone tell me what the standard is?

Quotes are bad camp

Chrome

{"label":1111} - SyntaxError: Unexpected token :

{label:1111} - Works

Firefox

{"label":1111} - SyntaxError: invalid label

{label:1111} - Works

Quotes are good camp

JSLint

{"video_id":1111} - JSON: good.

{video_id:1111} - JSON: bad. Expected a string and instead saw 'video_id'

PHP

echo json_encode(array('label' => 1111));
{"label":1111}
Share Improve this question edited Jan 16, 2013 at 19:14 quickshiftin asked Jan 16, 2013 at 19:07 quickshiftinquickshiftin 69.9k11 gold badges72 silver badges98 bronze badges 4
  • 1 You want JSONLint, not JSLint. – ithcy Commented Jan 16, 2013 at 19:09
  • If you look at the result of {label:1111} in the console, you wouldn't say that. – SLaks Commented Jan 16, 2013 at 19:10
  • Also: The standard is available on json, but to save you some reading, the standard requires quotes around labels. – ithcy Commented Jan 16, 2013 at 19:11
  • 2 WOW, I'd not realized there was a difference between Javascript objects and JSON. Thanks everyone for the clarification! – quickshiftin Commented Jan 16, 2013 at 19:17
Add a ment  | 

1 Answer 1

Reset to default 13

The standard is to parse JSON as JSON.

The JSON language (unlike Javascript) always requires all property names to be surrounded by double-quotes.

Your syntax errors e from trying to parse JSON as Javascript statements. The {} is parsed as a statement block, and the label: is parsed as a GOTO target.
Since statement labels cannot have quotes, this results in a syntax error.

If you wrap the JSON literals in parentheses to force Javascript to parse them as expressions, you won't get that error.

本文标签: phpCorrect label syntax for JSON objectStack Overflow