1

I am having trouble parsing a JSON Object with an Array and get the value based on the Key. I do this in one of my android application. I am planning to port the app to web application. In android I do something like this:

Lets say my json is like this:

{"radios":[{"name":"radio1","url":"url1"},{"name":"radio2","url":"url2"}, {"name":"radio3","url":"url3"}] }

My code looks like this in Android:

JSONArray radioListArray = jsonObject.getJSONArray("radios");
ArrayList<String> radioUrlColl = new ArrayList<String>();
    for(int i=0; i<radioListArray.length(); i++) {
            JSONObject radObject = radioListArray.getJSONObject(i);
            radioUrlColl.add(radObject.getString("url"));
    }
 Intent radioIntent = new Intent(arg0.getContext(), PlayerActivity.class);
            String url =radioUrlColl.get(arg2); //I get the URL here
            radioIntent.putExtra("radioUrl", url);

Basically, I get the url based on the position of the Clicked item in the list view. Is there a simpler solution where i would pass the key say radio1 and get the corresponding value url1 in Javascript

1 Answer 1

2

Is there a simpler solution where i would pass the key say radio1 and get the corresponding value url1 in Javascript

No, with the structure of that data, you still have to loop through the entries looking for the entry with the matching name property.

So say obj is the result of calling JSON.parse on the string containing that JSON text, and targetRadio is the radio you want. obj.radios will be the array. So you can use a simple for loop:

var n;
var url;
for (n = 0; n < obj.radios.length; ++n) {
    if (obj.radios[n].name === targetRadio) {
        url = obj.radios[n].url;
        break;
    }
}

Or if you want to rely on ES5's array enhancements (which can be shimmed if necessary), you could use some:

var url;
obj.radios.some(function(entry) {
    if (entry.name === targetRadio) {
        url = entry.url;
        return true; // To stop looping
    }
});
Sign up to request clarification or add additional context in comments.

1 Comment

Great Answer! Appreciated!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.