Search code examples
javascriptjsongetjson

Get information from varying objects in JSON


I have this code (which is variant thought the time) in JSON

{
  "5780": {
    "app": "Bye",
    "name": "Hello World",
    "surname": "Friend"
  },
  "6654": {
    "app": "Hello",
    "name": "Hi",
    "surname": "godbye"
  }
}

I want to get the information from each section (for example the "app" section) an insert in a js variable. The problem is that the object title (5780 & 6654) change will change (at the same time, the sections information). So I need something like section[1].app = jsvariable1


Solution

  • First of all, your json is not valid so you have to check it(as i did in the code below) . So here's what i did :

    var sections = {
      "5780": {
        "app": "Bye",
        "name": "Hello World",
        "surname": "Friend",
      },
    
      "6654": {
        "app": "Hello",
        "name": "Hi",
        "surname": "godbye",
      }
    
    };
    
    
    var index = [];
    
    //setting the index array
    for (var x in sections) {
      index.push(x);
    }
    
    console.log(sections[index[0]].app)
    console.log(sections[index[1]].app)