How to retrieve JSON Text using index?
I'm getting the jsontex开发者_开发知识库t from the database as (id,val) and I have to set the id name to the radio button id name and value as the display name or value of the radio button. JSON.parse will give the value, only If I specify the name of the id. Is it possible to retrieve the value by giving index. And how will I get the id name too? Example:
var dbDets = JSON.parse(jsontext);
var s=dbDets[0];
alert(s["DB001"]); //This is working
alert(s[0]);//This is not working.
My requirement is how to retrieve both id and value using index or by some way. Json Text is
[{"DB001":"emap","DB002":"sampledb","DB003":"webuserstat"}]
I think this is what you mean. Here's how to iterate through the properties of an object. If it's an object (and not an array) you can only obtain its members by name, not by index.
for (var i=0;i<dbDets.length;i++) {
for (var prop in dbDets[i]) {
if (dbDets.hasOwnProperty(prop)) {
alert('index:' + i + ',name:'+prop+', value:' + dbDets[i][prop]);
}
}
}
it may be that you want to serialize the data differently, so that each item has consistently named properties, and store the key ("DB001") as a value in an object instead of using it as a property name.
I'm assuming that array dbDets
looks like this:
[{ DB001: "somevalue"}, {DB002: "somevalue"}, ... ]
It would be easier to use the information if you store the data like this:
[{ id:"DB001", value: "somevalue"}, {id: "DB002", value: "somevalue"}, ... ]
Then you can just say access it like dbDets[index].id
and dbDets[index].value
精彩评论