Así que tengo este JSON:
{ "success": { "total": 1 }, "contents": { "quotes": [ { "quote": "When you win, say nothing. When you lose, say less.", "length": "51", "author": "Paul Brown", "tags": { "0": "inspire", "1": "losing", "2": "running", "4": "winning" }, "category": "inspire", "language": "en", "date": "2022-03-05", "permalink": "https://theysaidso.com/quote/paul-brown-when-you-win-say-nothing-when-you-lose-say-less", "id": "3dlKxoNAOZsB__Nb61H95weF", "background": "https://theysaidso.com/img/qod/qod-inspire.jpg", "title": "Inspiring Quote of the day" } ] }, "baseurl": "https://theysaidso.com", "copyright": { "year": 2024, "url": "https://theysaidso.com" } }Estoy tratando de capturar el texto en los campos de autor y cita en dos variables respectivas. Ya asigné la variable JSON al contenido de json. Lo que tengo ahora es lo siguiente a continuación que no funciona.
QUOTE = JSON.contents.quotes[0].quote; AUTHOR = JSON.contents.quotes[0].author;¿Qué estoy haciendo mal? ¿Y cuál sería el enfoque correcto?
¿Necesitaste el archivo json? Funciona bien para mí. también agregue let o var antes de la variable
var json = require('./2.json') let QUOTE = json.contents.quotes[0].quote; let AUTHOR = json.contents.quotes[0].author; console.log(QUOTE, AUTHOR); esta salida es When you win, say nothing. When you lose, say less. Paul Brown
Ya asigné la variable JSON al contenido de json.
Según su explicación, asumo que asignó el objeto de contents a la variable JSON . En ese caso, necesitaba acceder a las propiedades mediante JSON.quotes[0].quote y JSON.quotes[0].author . Consulte el fragmento a continuación.
var yourObject = { "success": { "total": 1 }, "contents": { "quotes": [{ "quote": "When you win, say nothing. When you lose, say less.", "length": "51", "author": "Paul Brown", "tags": { "0": "inspire", "1": "losing", "2": "running", "4": "winning" }, "category": "inspire", "language": "en", "date": "2022-03-05", "permalink": "https://theysaidso.com/quote/paul-brown-when-you-win-say-nothing-when-you-lose-say-less", "id": "3dlKxoNAOZsB__Nb61H95weF", "background": "https://theysaidso.com/img/qod/qod-inspire.jpg", "title": "Inspiring Quote of the day" }] }, "baseurl": "https://theysaidso.com", "copyright": { "year": 2024, "url": "https://theysaidso.com" } } let JSON = yourObject.contents let yourQuote = JSON.quotes[0].quote let yourAuthor = JSON.quotes[0].author console.log(yourQuote) console.log(yourAuthor)