0

Here is my code:

<script>
try {
    var ob = JSON.parse("{ ID: 1, 'Code':'001', 'Name':'john', 'HasParent':false, 'HasGrandParent':false, 'IsAgent':False }");
    document.write(ob.Name);
}
catch(err) {
    document.write(err);
}
</script>

Here is the error message:

Unexpected token I in JSON at position 2

I have no idea what's happening. What's wrong here?

==================

Thanks for the answer from JayTheKay below.

The problems and fixes are:

  1. use double quote for string
  2. boolean value is lower case, so "False" is wrong, "false" is correct
  3. this first key name ID is not wrapped with double quote
mjb
  • 7,649
  • 8
  • 44
  • 60

1 Answers1

3

JSON properties may not be enclosed in single quotes, you have to use double quotes. Take a look at this similar question: https://stackoverflow.com/a/36038497/891279

Your first property is not enclosed in quotes at all. This probably causes the error.

JayTheKay
  • 1,463
  • 12
  • 22
  • When you find a similar question, please flag it as a duplicate instead of posting an answer with a link to the question. Under the question, flag -> duplicate -> paste the URL in the box. – adiga Sep 15 '20 at 08:41
  • @adiga Actually, I was totally initially have no idea this has relation with the single quote or double quote. So, when I search the result in google, due to I didn't search for "single quote" in google search or stackoverflow search, I only search for the error message, and thus non related search result came out :) but nonetheless, thanks for you guys time in helping me :) – mjb Sep 15 '20 at 08:50
  • @adiga look at the tutorial here: https://www.w3schools.com/jsref/jsref_obj_json.asp It showed the example in double quote, but it didn't mention it must use double quote and I thought it works the same as HTML tag handles double quote and single quote. as javascript also accept double quote and single quote as string, that's why I was confused initially :) – mjb Sep 15 '20 at 08:52
  • 1
    @mjb your question is valid. My comment was for JayTheKay on how to flag from next time onwards if they find a duplicate. – adiga Sep 15 '20 at 09:02
  • 1
    @mjb also, please refer to [MDN](https://developer.mozilla.org/) instead of w3schools. Some of the stuff on w3schools is outdated and wrong ([Why not w3schools.com?](https://meta.stackoverflow.com/questions/280478)) – adiga Sep 15 '20 at 09:04