user2902458
user2902458

Reputation: 15

How can I get this link while parsing JSON?

I've been trying to get the mobile link from this API but I haven't been successful

.done(function( data ) {    
                var ol = $("<ol/>");

            $.each( data.headlines, function(h_key, headlines) {
var h2 = $( "<h2/>" ).append(headlines.headline);
 var a = $( "<a/>" ).attr("href", headlines.links.mobile);

ol.append(h2)
 ol.append(a)

This is the response body I'm trying to get the link from

{
"timestamp": "2013-10-21T14:50:18Z",
"resultsOffset": 0,
"status": "success",
"resultsLimit": 10,
"resultsCount": 27,
"headlines": [{
    "headline": "Portugal land Sweden in playoff draw",
    "keywords": ["UEFA WCQ: Portugal land Sweden in playoff draw"],
    "lastModified": "2013-10-21T14:17:13Z",
    "audio": [],
    "premium": false,
    "mobileStory": "",
    "links": {
        "api": {
            "news": {
                "href": "http://api.espn.com/v1/sports/news/1588808?region=GB"
            }
        },
        "web": {
            "href": "http://espnfc.com/news/story/_/id/1588808/portugal-land-sweden-playoff-draw?ex_cid=espnapi_public"
        },
        "mobile": {
            "href": "http://m.espn.go.com/soccer/story?storyId=1588808&ex_cid=espnapi_public"
        }
    },

Upvotes: 0

Views: 66

Answers (2)

Anand Jha
Anand Jha

Reputation: 10714

Try This,

var h2 = $( "<h2/>" ).append(headlines[0].headline);
var a = $( "<a/>" ).attr("href", headlines[0].links.mobile.href);

Upvotes: 0

David
David

Reputation: 218798

headlines is an array. Also, mobile still has another component to drill down into. Try this:

headlines[0].links.mobile.href

You'll probably want to add some runtime checking to make sure there's an element in headlines before you index it, of course.

A good way to test things like this is in your browser debugging tools. Usually you can put a break point in the debugger and see the structure of the JSON object. Some quick trial-and-error of referencing components of that object on the JavaScript console will help you navigate its structure.

Edit: I just noticed that you're iterating the array, so more likely:

headlines.links.mobile.href

You might want to change the name of your iterator variable from headlines as it may cause confusion. headline seems like a sensible alternative.

Upvotes: 1

Related Questions