繁体   English   中英

我想 JSON 解析对象内的对象数组 - 正文中的文章,我该怎么做?

[英]I want to JSON Parse an array of objects inside an object - articles from the body, how can I do that?

我在 Alan Studio 中发出 api 请求,并且新闻 api 返回一个对象,我想从中解析“文章”并将其存储并将它们发送到我的反应代码以在新闻卡片上显示它们

但是当我从正文中解析文章时,文章变得未定义。我如何 JSON 解析它?



下面给出的是从新闻 api 返回的数据。

{
    "status": "ok",
    "totalResults": 10,
    "articles": [
        {
            "source": {
                "id": "bbc-news",
                "name": "BBC News"
            },
            "author": "BBC News",
            "title": "Monkeypox: Nigeria bans bushmeat to prevent virus spread",
            "description": "Experts say it is possible that the virus can be caught by eating meat from an infected animal.",
            "url": "http://www.bbc.co.uk/news/world-africa-61676841",
            "urlToImage": "https://ichef.bbci.co.uk/news/1024/branded_news/983B/production/_125017983_gettyimages-453645236.jpg",
            "publishedAt": "2022-06-02T17:22:28.5473137Z",
            "content": "By Chris EwokorBBC News, Abuja\r\nImage caption, Bushmeat is a delicacy in parts of Nigeria, but in other places it can be a vital source of food\r\nThe Nigerian government has banned the sale of bushmea… [+2373 chars]"
        },
        {
            "source": {
                "id": "bbc-news",
                "name": "BBC News"
            },
            "author": "BBC News",
            "title": "Ukraine war: Zelensky says Russia controls a fifth of Ukrainian territory",
            "description": "Ukraine's president says Russia has taken 20% of Ukraine's territory, as the war nears its 100th day.",
            "url": "http://www.bbc.co.uk/news/world-europe-61675915",
            "urlToImage": "https://ichef.bbci.co.uk/news/1024/branded_news/130F7/production/_125017087_hi076131363.jpg",
            "publishedAt": "2022-06-02T17:22:24.7575621Z",
            "content": "By Matt MurphyBBC News\r\nImage caption, A Russian soldier in Mariupol\r\nUkraine's President Volodymyr Zelensky says that Russian forces have seized 20% of his country's territory, as Moscow's invasion … [+5338 chars]"
        },
        {
            "source": {
                "id": "bbc-news",
                "name": "BBC News"
            },
            "author": "BBC News",
            "title": "Oklahoma hospital shooting: Five dead after gunman targets physician",
            "description": "Police say the man blamed the doctor for his back pain and had purchased a rifle only hours earlier.",
            "url": "http://www.bbc.co.uk/news/world-us-canada-61676811",
            "urlToImage": "https://ichef.bbci.co.uk/news/1024/branded_news/1307/production/_125017840_gettyimages-1241045718.jpg",
            "publishedAt": "2022-06-02T16:52:23.4616839Z",
            "content": "Image source, Getty Images\r\nImage caption, Police respond to the scene of Wednesday's shooting at St Francis Hospital\r\nPolice have said a gunman who killed three employees and a patient at an Oklahom… [+2376 chars]"
        },
        {
            "source": {
                "id": "bbc-news",
                "name": "BBC News"
            },
            "author": "BBC News",
            "title": "Canada says China 'buzzing' military flights in Asia",
            "description": "Canada called the incidents are unprofessional and potentially hazardous to aircrew in the Pacific.",
            "url": "http://www.bbc.co.uk/news/world-us-canada-61654043",
            "urlToImage": "https://ichef.bbci.co.uk/news/1024/branded_news/75B3/production/_125013103_gettyimages-1341999649.jpg",
            "publishedAt": "2022-06-02T13:37:19.2266278Z",
            "content": "By Bernd Debusmann JrBBC News, Washington\r\nImage source, Getty Images\r\nImage caption, Chinese military aircraft at an airshow in September 2021\r\nCanadian military aircraft operating in Asia have been… [+2007 chars]"
        },
        {
            "source": {
                "id": "bbc-news",
                "name": "BBC News"
            },
            "author": "BBC News",
            "title": "Depp-Heard trial: Why Johnny Depp lost in the UK but won in the US",
            "description": "Experts say key factors included having a jury trial and his lawyers using a specific legal tactic.",
            "url": "http://www.bbc.co.uk/news/world-us-canada-61673676",
            "urlToImage": "https://ichef.bbci.co.uk/news/1024/branded_news/6037/production/_125013642_gettyimages-1241024662.jpg",
            "publishedAt": "2022-06-02T12:22:23.3055092Z",
            "content": "By Robin Levinson-KingBBC News\r\nImage source, Getty Images\r\nIn 2020, Hollywood actor Johnny Depp lost a UK libel lawsuit against the Sun newspaper. But on Wednesday, he won a similar lawsuit against … [+2956 chars]"
        },
        {
            "source": {
                "id": "bbc-news",
                "name": "BBC News"
            },
            "author": "BBC News",
            "title": "Turkey wants be be called Türkiye in rebranding move",
            "description": "The country wants to be called Türkiye as part of a rebranding campaign launched by its president.",
            "url": "http://www.bbc.co.uk/news/world-europe-61671913",
            "urlToImage": "https://ichef.bbci.co.uk/news/1024/branded_news/17CDD/production/_125010579_bluemosquegetty.jpg",
            "publishedAt": "2022-06-02T11:07:25.2572035Z",
            "content": "Image source, @MevlutCavusoglu\r\nImage caption, Turkish Foreign Minister Mevlut Cavusoglu\r\nTurkey will be known as Türkiye at the United Nations from now on, after it agreed to a formal request from A… [+1736 chars]"
        },
        {
            "source": {
                "id": "bbc-news",
                "name": "BBC News"
            },
            "author": "BBC News",
            "title": "Texas school shooting victim's parents mourn 'best friend'",
            "description": "The parents of Alithia Ramirez say they want the world to remember their daughter through her art.",
            "url": "http://www.bbc.co.uk/news/world-us-canada-61669234",
            "urlToImage": "https://ichef.bbci.co.uk/news/1024/branded_news/11FC6/production/_125007637_p0cbl2cx.jpg",
            "publishedAt": "2022-06-02T10:07:17.1192126Z",
            "content": "Last week 10-year-old Alithia Ramirez was shot and killed when a gunman opened fire at her primary school in Uvalde, Texas. \r\nHer parents say they want the world to remember their daughter was good a… [+168 chars]"
        },
        {
            "source": {
                "id": "bbc-news",
                "name": "BBC News"
            },
            "author": "BBC News",
            "title": "Bill Cosby 'pounced' on teen in Playboy Mansion",
            "description": "The comedian's lawyers dismiss the latest claim against him - stemming from 1975 - as a \"fabrication\".",
            "url": "http://www.bbc.co.uk/news/world-us-canada-61664500",
            "urlToImage": "https://ichef.bbci.co.uk/news/1024/branded_news/64DC/production/_125002852_gettyimages-1040552476.jpg",
            "publishedAt": "2022-06-02T07:37:18.1596491Z",
            "content": "Image source, Getty Images\r\nImage caption, Bill Cosby at his sentencing in Pennsylvania in 2018\r\nLess than a year after his sex assault conviction was thrown out and he walked free from prison, comed… [+2473 chars]"
        },
        {
            "source": {
                "id": "bbc-news",
                "name": "BBC News"
            },
            "author": "BBC News",
            "title": "Queen’s Platinum Jubilee: Trooping the Colour to begin celebrations",
            "description": "The Queen's Birthday Parade will kick off four days of celebrating the monarch's 70-year reign.",
            "url": "http://www.bbc.co.uk/news/live/uk-61516564",
            "urlToImage": "https://m.files.bbci.co.uk/modules/bbc-morph-news-waf-page-meta/5.2.0/bbc_news_logo.png",
            "publishedAt": "2022-06-02T06:07:24.9486456Z",
            "content": "Trooping the Colour is an annual military parade that marks the Queens official birthday - which this year falls on 11 June (her actual birthday is 21 April).\r\nThis is a centuries-old tradition which… [+973 chars]"
        },
        {
            "source": {
                "id": "bbc-news",
                "name": "BBC News"
            },
            "author": "BBC News",
            "title": "Depp-Heard trial: Jury sides mostly with Depp in defamation case",
            "description": "Jurors award Mr Depp $15m in compensatory and punitive damages, but also award Ms Heard $2m.",
            "url": "http://www.bbc.co.uk/news/world-us-canada-61668780",
            "urlToImage": "https://ichef.bbci.co.uk/news/1024/branded_news/12926/production/_125007067_tv076335814.jpg",
            "publishedAt": "2022-06-02T01:37:20.4013741Z",
            "content": "Media caption, Watch: Depp v Heard defamation case concludes in court\r\nA US jury has found Amber Heard defamed ex-husband Johnny Depp with an article in which she claimed she was a victim of domestic… [+4697 chars]"
        }
    ]
}

 // News by Source intent('Give me the news from $(source* (.*))', (p) => { let NEWS_API_URL = `https://newsapi.org/v2/top-headlines`; if(p.source.value) { NEWS_API_URL = `${NEWS_API_URL}?sources=${p.source.value.toLowerCase().split(" ").join('-')}&apiKey=${API_KEY}`; } api.request(NEWS_API_URL, (error, response, body) => { const { articles } = JSON.parse(body); console.log(articles); // returns undefined if(articles?.length === 0) { p.play('Sorry, please try searching for news from a different source'); return; } savedArticles = articles; p.play({ command: 'newHeadlines', articles }); p.play(`Here are the (latest|recent) ${p.source.value}.`); p.play('Would you like me to read the headlines?'); p.then(confirmation); }); })

这里的问题是 API 请求期望从 API 调用返回一个承诺,这是一个正在工作并返回数据的快速代码片段(只需在 URL 中替换您的 API 密钥。

 // API CALL START HERE let data = fetch("https://newsapi.org/v2/top-headlines?country=us&apiKey=<your api key here>") .then(function(response) { // This returns the promise from the API request which processes the data return response.json(); }) .then(function(data) { // Loop through the data returned for articles and console log each specific article for (const article in data.articles ) { console.log(data.articles[article]); } });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM