4

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'
benVG
  • 603
  • 3
  • 14
  • 25

3 Answers3

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

In modern browsers:

var names = Object.keys( jsonobj.Table );
elclanrs
  • 92,861
  • 21
  • 134
  • 171
1

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.

Julien Royer
  • 1,419
  • 1
  • 14
  • 27
0

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);
      });
    }
});
Jai
  • 74,255
  • 12
  • 74
  • 103