Accessing elements of JSON object without knowing the key names

Here's my json:

{"d":{"key1":"value1",
      "key2":"value2"}}

Is there any way of accessing the keys and values (in javascript) in this array without knowing what the keys are?

The reason my json is structured like this is that the webmethod that I'm calling via jquery is returning a dictionary. If it's impossible to work with the above, what do I need to change about the way I'm returning the data?

Here's an outline of my webmethod:

<WebMethod()> _
Public Function Foo(ByVal Input As String) As Dictionary(Of String, String)
    Dim Results As New Dictionary(Of String, String)

    'code that does stuff

    Results.Add(key,value)
    Return Results
End Function

You can use the for..in construct to iterate through arbitrary properties of your object:

for (var key in obj.d) {
    console.log("Key: " + key);
    console.log("Value: " + obj.d[key]);
}

Is this what you're looking for?

var data;
for (var key in data) {
   var value = data[key];
   alert(key + ", " + value);
}

{
  "d":{
     "key1":"value1",
     "key2":"value2"
    }
}

To access first key write:

   let firstKey=Object.keys(d)[0];

To access value of first key write:

let firstValue= d[firstKey];

By using word "b", You are still using key name.

var info = {
"fname": "Bhaumik",
"lname": "Mehta",
"Age": "34",
"favcolor": {"color1":"Gray", "color2":"Black", "color3":"Blue"}
};

Look at the below snippet.

for(key in info) {
  var infoJSON = info[key];
  console.log(infoJSON);
}

Result would be,

Bhaumik
Mehta
Object {color1: "Gray", color2: "Black", color3: "Blue"} 

Don’t want that last line to show up? Try following code:

for(key in info) {
  var infoJSON = info[key];
    if(typeof infoJSON !== "object"){
       console.log(infoJSON);
  }
}

This will eliminate Object {color1: “Gray”, color2: “Black”, color3: “Blue”} from showing up in the console.

Now we need to iterate through the variable infoJSON to get array value. Look at the following whole peace of code.

for(key in info) {
    var infoJSON = info[key];
    if (typeof infoJSON !== "object"){
       console.log(infoJSON);
    }
 }

for(key1 in infoJSON) {
    if (infoJSON.hasOwnProperty(key1)) {
       if(infoJSON[key1] instanceof Array) {
          for(var i=0;i<infoJSON[key1].length;i++) {
             console.log(infoJSON[key1][i]);
          }
        } else {console.log(infoJSON[key1]);}
    }
 }

And now we got the result as

Bhaumik
Mehta
Gray
Black
Blue

If we use key name or id then it’s very easy to get the values from the JSON object but here we are getting our values without using key name or id.


Use for loop to achieve the same.

var dlist = { country: [ 'ENGLAND' ], name: [ 'CROSBY' ] }

for(var key in dlist){
     var keyjson = dlist[key];
     console.log(keyjson)
   }