2

I'm new and learning JSON but I have been having an issue with displaying some API results:

$.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 works fine but how do I list the text of all the matches using JSON (above) into an HTML list assuming this is the endpoint: http://api.alquran.cloud/v1/search/abraham/all/en

Michał Ziober
  • 37,175
  • 18
  • 99
  • 146

2 Answers2

1

In your API response matches is an array of object. So you need to iterate the loop to access the text value

$.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;
})

Otherwise if you want a single data, get it using index value. Like below code

arText = data.data.matches[0].text;
document.getElementById('demo').innerHTML = arText;
mkHun
  • 5,891
  • 8
  • 38
  • 85
1

matches is a JSON Array. You need to iterate over elements and grab text property. Also, remember to declare variables in handler function with const, let or var.

$.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;
})
Michał Ziober
  • 37,175
  • 18
  • 99
  • 146
  • 1
    @mkHun, good point. Of course we need to take under consideration one side effect: map function creates extra array with transformed elements. After that we need to iterate it again to join all elements to a String variable. Your for-of solution is definitely faster. In case user would like to provide some filter function or do more sophisticated modification on input array this approach allows easier way to implement it. Also, `String` concat is faster: [Array Join vs String Concat](https://stackoverflow.com/questions/7296594/array-join-vs-string-concat). But it depends from implementation. – Michał Ziober Oct 06 '20 at 12:10