最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Getting property key from json object - Stack Overflow

programmeradmin4浏览0评论

Preamble: I'm Italian, sorry for my bad English.

I need to retrieve the name of the property from a json object using javascript/jquery.

for example, starting from this object:

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

is there a way to get the strings "Name" and "Surname"?

something like:

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

Preamble: I'm Italian, sorry for my bad English.

I need to retrieve the name of the property from a json object using javascript/jquery.

for example, starting from this object:

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

is there a way to get the strings "Name" and "Surname"?

something like:

//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'
Share Improve this question asked Dec 17, 2012 at 10:15 benVGbenVG 6133 gold badges14 silver badges26 bronze badges 1
  • 1 Look at this: stackoverflow./questions/8430336/… – Darin Kolev Commented Dec 17, 2012 at 10:20
Add a ment  | 

3 Answers 3

Reset to default 10
var names = [];
for ( var o in jsonobj.Table ) {
  names.push( o ); // the property name
}

In modern browsers:

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

You can browse the properties of the object:

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

The hasOwnProperty test is necessary to avoid including properties inherited from the prototype chain.

In jquery you can fetch it like this:

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

评论列表(0)

  1. 暂无评论