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
  • 22,351
  • 6
  • 45
  • 63
user3701584
  • 115
  • 2
  • 7

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
  • 1,985
  • 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
  • 499
  • 2
  • 14
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
  • 9,544
  • 7
  • 47
  • 59
pawas
  • 1
  • 1
  • 2