Accessing JSON Array Data Without Knowing Its Keys

Suppose a json file contains the following array

[{"keyABC":"R"},{"key123":"J"},{"keyDEF":"H"}]

How can I get the key using just the index of the array using jQuery?

Hey,

So this seems to work:

var json = [{"keyABC":"R"},{"key123":"J"},{"keyDEF":"H"}];

for (var i = 0; i < json.length; i++){
    var obj = json[i];
    for (var key in obj){
        var attrName = key;
        var attrValue = obj[key];
        console.log(attrName)
    }
}

Taken from https://stackoverflow.com/questions/1078118/how-do-i-iterate-over-a-json-structure

Random access of an array is already possible, regardless of what’s IN the array.

json[Math.random(json.length)]

There’s no value in randomly naming the keys in your objects; the objects should be a standard form.

[{key:"ABC",question:"Question: ABC is known as",answer:"Alphabetic"},{key:"XYZ",question:"What are the last 3 letters of the alphabet?",answer:"XYZ"},...]

2 Likes

Thank you all for your reply. I was able to get the solution that mrlagmer provided to work by incorporating the random number generator function into the solution.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.