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

1
  • Can you please describe that actually which result you want? I mean sample output you want? Commented Oct 6, 2020 at 11:31

2 Answers 2

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; 
Sign up to request clarification or add additional context in comments.

6 Comments

How would I put each result in an li tag?
Thanks so much! I would upvote but I dont have any points
No worries. But you can accept my answer :)
Oh, when I accepted an answer, I have enough points to upvote, lol
What if I wanted to get the surah name.
|
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; }) 

1 Comment

@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. But it depends from implementation.