【问题标题】:how can i access the object properties that have spaces [duplicate]我如何访问有空格的对象属性[重复]
【发布时间】:2017-05-26 09:17:48
【问题描述】:

在下面的 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"
    }
  }
}

【问题讨论】:

    标签: json


    【解决方案1】:

    不确定您的要求,但期望低于 sn-p 可能会有所帮助

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

    【讨论】:

      【解决方案2】:

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

      data['personal details']
      

      对于所有其他带有空格和单个单词的键都相同

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

      但最好使用.dot 表示法作为单字 json 键

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

      【讨论】:

        猜你喜欢
        • 2019-02-04
        • 2012-09-29
        • 2011-08-27
        • 2019-12-27
        • 1970-01-01
        • 2023-03-04
        • 2018-10-18
        • 2014-06-30
        • 1970-01-01
        相关资源
        最近更新 更多