简体   繁体   中英

how to read json object when i don`t know the name of the key

in runtime i will have a dynamic dictionary object return to me

eg var objectFromApi = {"A ":"I am A","B":"I am B","C":"I am C"}

i cannot do objectFromApi ["A"] to get the value, since i won`t able to know the key.

is there a way to print all the key and its value?

is there something like

for(j=0;j<objectFromApi.length;j++)
{
    console.debug(objectFromApi[j].Key +"  " + objectFromApi[j].Value);
}

Thanks

for(var name in objectFromApi )
{
    if (objectFromApi.hasOwnProperty(name))
    {

    }
}

http://jsfiddle.net/V6t6Y/

In ECMA 5 you can also use

var keys = Object.keys(objectFromAPi)

which will return

 ["A ", "B", "C"]

then you can iterate over the array like you normally would

for(var i = 0; i < keys.length; i++){
     // do something with the value
     // objectFromApi[keys[i]] 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM