0

I am using wikipedia API my json response looks like,

"{
    "query": {
        "normalized": [
            {
                "from": "bitcoin",
                "to": "Bitcoin"
            }
        ],
        "pages": {
            "28249265": {
                "pageid": 28249265,
                "ns": 0,
                "title": "Bitcoin",
                "extract": "<p><b>Bitcoin</b>isapeer-to-peerpaymentsystemintroducedasopensourcesoftwarein2009.Thedigitalcurrencycreatedandlikeacentralbank,
andthishasledtheUSTreasurytocallbitcoinadecentralizedcurrency....</p>"
            }
        }
    }
}"

this response is coming inside XMLHTTPObject ( request.responseText )

I am using eval to convert above string into json object as below,

var jsonObject = eval('(' +req.responseText+ ')');

In the response, pages element will have dynamic number for the key-value pair as shown in above example ( "28249265" )

How can I get extract element from above json object if my pageId is different for different results.

Please note, parsing is not actual problem here,

If Parse it , I can acess extract as,

var data = jsonObject.query.pages.28249265.extract;

In above line 28249265 is dynamic, This will be something different for different query

Pradeep
  • 6,303
  • 9
  • 36
  • 60
  • possible duplicate of [How to parse JSON in JavaScript](http://stackoverflow.com/questions/4935632/how-to-parse-json-in-javascript) – J0HN Apr 10 '14 at 06:14
  • No I don't think it's duplicate, please check last line – Pradeep Apr 10 '14 at 06:19

2 Answers2

1

assuming that u want to traverse all keys in "jsonObject.query.pages". u can extract it like this:

var pages = jsonObject.query.pages;
for (k in pages) { // here k represents the page no i.e. 28249265
    var data = pages[k].extract;
    // what u wana do with data here
}

or u may first extract all page data in array.

var datas = [];
var pages = jsonObject.query.pages;
for (k in pages) {
    datas.push(pages[k].extract);
}
// what u wana do with data array here
0

you can archive that using two methods

obj = JSON.parse(json)

OR

obj = $.parseJSON(json);

UPDATE

Try this this

var obj = JSON.parse("your json data string");

//console.log(obj)

jQuery.each(obj.query.pages,function(a,val){
// here you can get data dynamically
  var data = val.extract;
  alert(val.extract);

});

JSBIN Example JSBIN

Anant Dabhi
  • 10,864
  • 3
  • 31
  • 49