【问题标题】:Getting property key from json object从 json 对象获取属性键
【发布时间】:2012-12-04 10:18:52
【问题描述】:

序言:我是意大利人,抱歉我的英语不好。

我需要使用 javascript/jquery 从 json 对象中检索属性的名称。

例如,从这个对象开始:

{
      "Table": {
          "Name": "Chris",
          "Surname": "McDonald"
       }
}

有没有办法获取字符串“Name”和“Surname”?

类似:

//not working code, just for example
var jsonobj = eval('(' + previouscode + ')');
var prop = jsonobj.Table[0].getPropertyName();
var prop2 = jsonobj.Table[1].getPropertyName();
return prop + '-' + prop2; // this will return 'Name-Surname'

【问题讨论】:

标签: javascript jquery json object properties


【解决方案1】:
var names = [];
for ( var o in jsonobj.Table ) {
  names.push( o ); // the property name
}

在现代浏览器中:

var names = Object.keys( jsonobj.Table );

【讨论】:

    【解决方案2】:

    您可以浏览对象的属性:

    var table = jsonobj.Table;
    for (var prop in table) {
      if (table.hasOwnProperty(prop)) {
        alert(prop);
      }
    }
    

    hasOwnProperty 测试对于避免包含从原型链继承的属性是必要的。

    【讨论】:

      【解决方案3】:

      在 jquery 中你可以这样获取它:

      $.ajax({
          url:'path to your json',
          type:'post',
          dataType:'json',
          success:function(data){
            $.each(data.Table, function(i, data){
              console.log(data.name);
            });
          }
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-26
        • 1970-01-01
        • 2016-06-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多