1
var s = '{"1" : "Sammy", "2" : "Shark", "3" : "Ocean"}';

var obj = JSON.parse(s);

document.getElementById("user").innerHTML =
"Name: " + obj.1 + " " + obj.2 + "<br>" +
"Location: " + obj.3;

Error from console:

Uncaught SyntaxError: Unexpected number
31piy
  • 23,323
  • 6
  • 47
  • 67
user3701584
  • 115
  • 2
  • 8

3 Answers3

4

Use bracket notation to access numeric keys of an object:

const obj = { "1": "Sammy" };
console.log(obj["1"]);

Same goes for using some other character, for example -:

const obj = { "test-123": "works only with bracket notation" };
console.log(obj["test-123"]);

As gurvinder372 suggests, identifier cannot be numeric, you tried to access object's property with a number, which is wrong.

Tomasz Bubała
  • 2,093
  • 1
  • 11
  • 18
0

Correct Code

var s = JSON.parse('{"1" : "Sammy", "2" : "Shark", "3" : "Ocean"}');

document.getElementById("user").innerHTML =
"Name: " + s["1"] + " " + s["2"] + "<br>" +
"Location: " + s["3"];
Saurabh Pandey
  • 519
  • 2
  • 15
0

you cannot have numbers after . (dot operator) you should try using [].

var s = '{"1" : "Sammy", "2" : "Shark", "3" : "Ocean"}';

var obj = JSON.parse(s);

document.getElementById("user").innerHTML =
"Name: " + obj[1] + " " + obj[2] + "<br>" +
"Location: " + obj[3];
BlackBeard
  • 10,246
  • 7
  • 52
  • 62
pawas
  • 1
  • 1
  • 2