how can i access the object properties that have spaces

in the below json file i want to access the "personal details", but how can i do that, it different from other object keys, Any help please..

{
"data": {
    "personal details": {
        "name": "Loren",
        "father's name'": "Geroge",
        "mother's name": "Lita"
    },
    "class": {
        "name": "Loren Gothem",
        "class": 7,
        "division": "3rd"
    },
    "address": {
        "temporary address": "Acn Block Ist Phase",
        "permanent address": "Bozane Trail Building Ist Floor"
    }
  }
}

2 answers

  • answered 2017-01-11 14:20 p0k8_

    You can access using bracket notation

    data['personal details']
    

    same for all the other keys with spaces as well as with a single word

    data['personal details']['name']
    

    but it's better to use .dot notation for single word json keys

    data['personal details'].name //  "Loren" 
    data.address['temporary address'] // prints "Acn Block Ist Phase"
    

  • answered 2017-01-11 14:20 kakurala

    Am not sure about your requirement but expecting below snippet may help

    var a = {
    "data": {
        "personal details": {
            "name": "Loren",
            "father's name'": "Geroge",
            "mother's name": "Lita"
        },
        "class": {
            "name": "Loren Gothem",
            "class": 7,
            "division": "3rd"
        },
        "address": {
            "temporary address": "Acn Block Ist Phase",
            "permanent address": "Bozane Trail Building Ist Floor"
        }
      }
    };
    
    // with JQuery
    $.each(a.data, function(i,j){
    document.writeln(JSON.stringify(a.data[i]));
    })
    
    // with Javascript for..each loop
    for(b in a.data){
        document.writeln(a.data[b].name);
    
    //  if(b == "personal details"){
    //      do something else
    //  }
    
    }