0

My JScript is:

var t={'color':'red'}; // dynamic json data.
for(n in t)
{
    alert(n)
}

here, alert gives the json key color. but how to get its value?

Note: the json is dynamic.

Natesan
  • 1,135
  • 2
  • 14
  • 21

4 Answers4

7
var t={'color':'red'}; // dynamic json data.
for(n in t)
{
    alert(n);// n = key
    var val =t[n];// value where key is n

}
vikrant singh
  • 2,091
  • 1
  • 12
  • 16
2

Here is a simple example to get dynamic keys from json response - Get dynamic keys from JSON Data

public void getData(String data){
    // Load json data and display
JSONObject jsonData = new JSONObject(data);
// Use loop to get keys from your response
Iterator itr = jsonData.keys();
while(itr.hasNext()){
    String keys = (String)itr.next();
Log.e("Keys", "----"+keys);

JSONArray dynamicValue = jsonData.getJSONArray(keys);

    // Your stuff here
} }
Aneh Thakur
  • 1,072
  • 12
  • 20
0
var t={'color':'red'}; // dynamic json data.
for(n in t)
{
    alert(t[n])
}
revolver
  • 2,385
  • 5
  • 24
  • 40
-2

instead of putting the n in al alert put it in an external variable or something...

Edited, try sometnihg like this:

var ex_n;
var t={'color':'red'};

for(var i=0; i<t.length; i++) ex_n = t[i]["color"];
BRap
  • 529
  • 2
  • 10
  • 29
  • it gives the same output 'color'. but I want to access its value dynamically – Natesan Jul 11 '13 at 11:06
  • This would work for standard arrays without keys, his problem with associative arrays. see vikrant singh's answer – rorypicko Jul 11 '13 at 11:18
  • 1
    Yes but this also works with an associative array(if you know the name of the key), try yourself.. – BRap Jul 11 '13 at 11:26