解析由mediawiki API返回的响应。

huangapple go评论247阅读模式
英文:

Parsing response returned by mediawiki api

问题

程序相当简单(这使我对它的每个方面都挣扎了很长时间,这更令人尴尬);HTML表单从用户那里获取输入;使用该输入作为搜索查询来查询媒体维基API,并获得响应。

我已经让这一部分工作,我可以呈现媒体维基返回的整个JSON对象。

从这里,我可以访问“pages”键的值。

但这并不容易阅读,所以我需要找出如何分别索引每个键,将这些值存储在某个JS对象中,然后我可以以正常方式显示这些值。

但是这比我想象的更困难。以下是我尝试过的一些方法。关于如何解析这个JSON对象以及为什么下面的方法失败了,有什么想法吗?

未能成功的方法

这两者都导致了“良性失败”,其中this.answer / this.ans_spec未定义

这两者都会导致JS块失败并进入catch块

英文:

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.

解析由mediawiki API返回的响应。

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

解析由mediawiki API返回的响应。

解析由mediawiki API返回的响应。

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

答案1

得分: 1

data.pages是一个对象数组,所以您只需要遍历它:

for (const page of data.pages) {
    console.log(page.id);
    console.log(page.excerpt);
    // ...等等
}
英文:

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
}

huangapple
  • 本文由 发表于 2023年6月8日 14:53:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/76429295.html