javascriptjsonfetchmediawiki-api

Parsing response returned by mediawiki api


PS - Scroll down to the bold italic thing for my question; everything else is context

The program is pretty simple (which makes how long I've struggled with every aspect of it even more embarrassing) ; html form takes an input from the user; queries the media wiki api using that input as the search query, gets the response.

I've gotten this much to work, & I can render the whole Json object media wiki returns.

enter image description here

From here I can access the value for the "pages" key.

enter image description here

enter image description here

But this is not easily readable, so I need to figure out how to index each of the keys separately, store those values in some JS object, & then I can display things in a normal way.

However this is proving more difficult than I'd have thought. Below are a bunch of things I tried. Any ideas on both how to parse this Json object & why the below things failed?

Things that did not work

this.answer = data.pages.excerpt
this.answer = data.pages
this.ans_spec = this.answer.excerpt

Both of the above resulted in "benign failures" where this.answer / this.ans_spec were undefined

this.answer = JSON.parse(data.pages)
this.answer = data.pages
this.ans_spec = JSON.parse(this.answer)

These properly caused the JS block to fail & go to the catch block


Solution

  • data.pages is an array of objects, so you just need to loop over it:

    for (const page of data.pages) {
        console.log(page.id);
        console.log(page.excerpt);
        // ...etc
    }