EnPep
EnPep

Reputation: 65

Adding a variable to json query

I have this piece of code:

[...]
var apiURL = "http://.../api.php?format=json";
$.getJSON(apiURL, function(jsonData) {
   $('#tr<?php echo $itemId; ?>').text( $(jsonData)[0].query.pages. + objId  );
});
[...]

Where objId is a javascript variable that can handle different values. How can I make this working? How can I add a variable to this json query?

The json is this one:

{
    "query": {
        "pages": {
            "6": {
                "pageid": 6,
                "ns": 0,
                "title": ".ODk.MTc5",
                "touched": "2013-05-03T10:22:37Z",
                "lastrevid": 26,
                "counter": 0,
                "length": 23,
                "new": "",
                "protection": [{
                        "type": "edit",
                        "level": "sysop",
                        "expiry": "infinity"
                    }
                ]
            }
        }
    }
}

Thanks!

Upvotes: 2

Views: 963

Answers (1)

Colin DeClue
Colin DeClue

Reputation: 2244

Here's what you need to do:

var apiURL = "http://.../api.php?format=json";
$.getJSON(apiURL, function(jsonData) {
   $('#tr<?php echo $itemId; ?>').text( jsonData.query.pages[objId]  );
});

jsonData is a valid JavaScript object, so you can just access its properties with either dot notation or bracket notation. Bracket notation takes in a string or integer (which is what I assume objId would be) and looks up the property based on that. Dot notation does what you'd expect from any object. There's no reason to try to create a jQuery object out of it first, since that would just not select anything.

Upvotes: 1

Related Questions