如何从JavaScript中的JSON有效负载获取所有匹配属性

问题描述

我是新手,正在学习JSON,但是在显示一些API结果时遇到了问题:

$.getJSON(url,function (data) {
    enText = data.data.count;
    arText = data.data.matches.text;
    document.getElementById('verseText').innerHTML = 'Matches: '+enText+'';
    document.getElementById('demo').innerHTML = arText;
})

enText可以正常工作,但是如何使用JSON(在上方)将所有匹配项的文本列出到HTML列表中 假设这是端点:http://api.alquran.cloud/v1/search/abraham/all/en

解决方法

在您的API响应中,matches是一个对象数组。因此,您需要迭代循环以访问text

$.getJSON("http://api.alquran.cloud/v1/search/abraham/all/en",function (data) {
    enText = data.data.count;
    arText = data.data.matches;

    var li= '';
    for (const x of arText) {
        li+='<li>'+x.text+' <span class="surah">'+x.surah.name+'</span></li>';

    }

    document.getElementById('verseText').innerHTML = 'Matches: ' + enText + '';
    document.getElementById('demo').innerHTML = li;
})

否则,如果要单个数据,请使用索引值获取它。像下面的代码

arText = data.data.matches[0].text;
document.getElementById('demo').innerHTML = arText;
,

matchesJSON Array。您需要遍历元素并获取text属性。另外,请记住在处理程序函数中使用constletvar声明变量。

$.getJSON(url,function (data) {
    const enText = data.data.count;
    const arText = data.data.matches
                       .map(m => `<li>${m.text}</li>`)
                       .join("");
    document.getElementById('verseText').innerHTML = 'Matches: '+enText+'';
    document.getElementById('demo').innerHTML = arText;
})