He estado tratando de extraer datos de una API de "Fuente de noticias actuales" estructurada en JSON usando Javascript. Estoy en las fases de prueba en este momento.
Al hacer clic, quiero que mi elemento HTML llamado "título" se actualice al "título del archivo News JSON. Esto es lo que tengo hasta ahora...
el html
<h3 class="title text-center" id="title" name="title">Russia accuses US of interfering in vote</h3> <button type="button" class="btn btn-outline-dark text-white bg-muted" id="searchButton">Search</button>El JavaScript
const title = document.getElementById("title"); const searchButton = document.getElementById("searchButton"); searchButton.addEventListener("click", getRandomTitle) function getRandomTitle() { fetch('https://api.currentsapi.services/v1/latest-news?q=keywords=Biden&apiKey=12345678910') .then(res => res.json()) .then(data => { title.innerHTML = data.news.title }); }El archivo JSON
{ "status": "ok", "news": [ { "id": "4e67842f-018d-4744-aa02-d21da55c278d", "title": "Early Matter Domination from Long-Lived Particles in the Visible Sector. (arXiv:2108.13136v2 [hep-ph] UPDATED)" ...data.news es una matriz de objetos, para acceder al título específico debe usar el índice correspondiente.
Además, le sugiero que use HTMLElement.innerText o Node.textContent para establecer el texto sin formato (no htmlString ) en un elemento HTML:
title.textContent = data.news[0].title; // get the title from first news objectDesde el archivo JSON, parece que data.news es una matriz.
Prueba data.news[0].title
Intente usar data.news[0].title porque parece que está obteniendo una variedad de objetos como resultado en data.news
function getRandomTitle() { fetch('https://api.currentsapi.services/v1/latest-news?q=keywords=Biden&apiKey=12345678910') .then(res => res.json()) .then(data => { title.innerHTML = data.news[0].title // Specify the index for the array });