Search code examples
javascriptjsonjsonpath

Javascript - How to write json path when there's an integer tag


Javascript:

var json_obj = 
{
   "1111": {
       "name": Bob,
       "id": 1
   },
   "2222": {
       "name": Alice,
       "id": 2
   }
}
var first_name = json_obj.1111.name; // Gives me a missing ';' before statement error

In above code, json_obj is a part of a large json file used in our project. I thought of changing json file to make it easy to locate elements but it is a large json file and is used throughout the project, can someone enlighten me as to how to locate elements in these situations?


Solution

  • In such case you can use bracket notation

    var json_obj = {
      "1111": {
        "name": "Bob",
        "id": 1
      },
      "2222": {
        "name": "Alice",
        "id": 2
      }
    }
    var first_name = json_obj['1111'].name;
    
    document.write(first_name);