0

I have a simple test JSON String:

<!DOCTYPE html>
<html>
<body>

<h2>JSON Object Creation in JavaScript</h2>

<p id="demo"></p>

<script>
var txt = '{"name":"Jimmy","street":"Hill Street","phone":"555 1234567"}';
//var txt = "{'name':'Jimmy','street':'Hill Street','phone':'555 1234567'}";

var obj = JSON.parse(txt);

document.getElementById("demo").innerHTML = 
obj.name + "<br>" +
obj.street + "<br>" +
obj.phone;
</script>

</body>
</html>

Why the first one works and the second one not?

Any rules for JSON string with double quotes/single quotes?

Thanks.

Jimmy
  • 1,699
  • 2
  • 16
  • 17
  • 3
    Yes, you can read about it on http://json.org/ and https://en.wikipedia.org/wiki/JSON#Data_types.2C_syntax_and_example . Same issue, different language: http://stackoverflow.com/q/4162642/218196 – Felix Kling Sep 25 '14 at 03:13
  • The official syntax allows only double quotes. Some parsers will apparently accept single quotes, but that's non-standard. – Hot Licks Sep 25 '14 at 03:15
  • Thanks. So when I generate JSON string from Java Code, it will be a troublesome to add so many \" in the string. – Jimmy Sep 25 '14 at 05:51
  • 1
    Better to create the appropriate Lists/Maps and use a JSON serializer. – Hot Licks Sep 25 '14 at 16:24

1 Answers1

1

JSON requires double quotes for string literals.

See json.org. For the JSON grammar in the context of JavaScript, see Sections 5.1.5 and 15.12.1 in the ECMAScipt Specification: http://www.ecma-international.org/ecma-262/5.1/#sec-5.1.5 .

aap
  • 897
  • 11
  • 15