我如何访问具有空格的对象属性

时间:2017-01-11 14:20:28

标签: json

在下面的json文件中我想访问"个人详细信息",但是我怎么能这样做,它与其他对象键不同。

{
"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 个答案:

答案 0 :(得分:1)

您可以使用括号表示法访问

data['personal details']

对于所有其他带空格的键以及单个单词

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

但是对单字json键使用.点符号会更好

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

答案 1 :(得分:0)

我不确定您的要求,但期望下面的代码段可能会有所帮助

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
//  }

}