Python Key 错误 json.loads 带括号

问题描述

因此,我正在尝试使用此新闻 API 来获取有关不和谐机器人的最新消息。我可以加载所有 json 文本,但是当我尝试访问某些键时,我收到错误消息。

{'status': 'ok','totalResults': 38,'articles': [{'source': {'id': 'cbc-news','name': 'CBC News'},'author': None,'title': 'More COVID-19 patients dying at home,Ontario coroner says - CBC.ca','description': 'Some COVID-19 patients are now deteriorating so quickly that they die before they can seek medical attention,Ontario\'s chief coroner says. He calls it an "unfortunate and sad" phenomenon that shows how serious the virus can be.','url': 'https://www.cbc.ca/news/canada/toronto/covid-patients-dying-at-home-ontario-coroner-1.6000327','urlToImage': 'https://i.cbc.ca/1.6000273.1619207608!/cpImage/httpImage/image.jpg_gen/derivatives/16x9_620/covid-ont-20200623.jpg','publishedAt': '2021-04-24T15:13:50Z','content': "Some COVID-19 patients are now becoming so ill so quickly that they die before seeking medical attention,Ontario's chief coroner said.\xa0\r\nAt least 25 people have died in their homes rather than in ho… [+2889 chars]"},{'source': {'id': 'cbc-news','title': 'Space station population grows to 11 after SpaceX capsule transport - CBC.ca','description': "The International Space Station's population swelled to 11 on Saturday with the jubilant arrival of SpaceX's third crew capsule in less than a year.",'url': 'https://www.cbc.ca/news/technology/space-station-population-spacex-1.6001084','urlToImage': 'https://i.cbc.ca/1.6001092.1619273762!/cpImage/httpImage/image.jpg_gen/derivatives/16x9_620/spacex-crew-dragon-spacecraft-approaches-the-iss.jpg','publishedAt': '2021-04-24T14:59:41Z','content': "The International Space Station's population swelled to 11 on Saturday with the jubilant arrival of SpaceX's third crew capsule in less than a year.\r\nIt's the biggest crowd at the station in more tha… [+3426 chars]"},{'source': {'id': None,'name': 'Global News'},'author': 'Aijaz Hussain','title': '‘It’s over’: India COVID-19 patients suffocate as cases surge during oxygen shortage - Global News','description': "India confirmed 346,786 COVID-19 cases over the past day,bringing the country's total to more than 16 million,behind only the United States.",'url': 'https://globalnews.ca/news/7786158/india-coronavirus-patients-oxyegen-shortage/','urlToImage': 'https://globalnews.ca/wp-content/uploads/2021/04/CP122169833.jpg?quality=85&strip=all&w=720&h=379&crop=1','publishedAt': '2021-04-24T13:46:40Z','content': 'Indian authorities scrambled Saturday to get oxygen tanks to hospitals where COVID-19 patients were suffocating amid the world’s worst coronavirus surge,as the government came under increasing criti… [+8106 chars]'},'name': 'Sportsnet.ca'},'title': 'Quick Shifts: Bad blood brewing between Maple Leafs and Jets - Sportsnet.ca','description': "Tensions and chirps heat up between Canada's best two teams,why David Pastrnak sent that Tom Wilson tweet,Patrick Marleau on track for the Hall of Fame,and can the NHL follow F1's binge-watching lead? That and much more.",'url': 'https://www.sportsnet.ca/nhl/article/toronto-maple-leafs-dirty-winnipeg-jets-simmonds-dubois/','urlToImage': 'https://www.sportsnet.ca/wp-content/uploads/2021/04/jets-leafs-april-15-1040x572.jpg','publishedAt': '2021-04-24T12:48:00Z','content': 'A quick mix of the things we gleaned from the week of hockey,serious and less so,and rolling four lines deep. Peace and Humptiness forever.\r\n1. For those of us who have watched the Toronto Maple Le… [+16892 chars]'},'author': 'Edna Tarigan And Fadlan Syam','title': 'Indonesia says missing sub sunk,cracked open,killing all 52 members on board - Global News','description': 'The cause of the disappearance was still uncertain,but the navy had previously said an electrical failure could have left the submarine unable to execute emergency procedures.','url': 'https://globalnews.ca/news/7786099/missing-submarine-indonesia-sunk-52-dead/','urlToImage': 'https://globalnews.ca/wp-content/uploads/2021/04/CP122059161-e1619235064309.jpg?quality=85&strip=all&w=720&h=379&crop=1','publishedAt': '2021-04-24T12:32:33Z','content': 'Indonesia’s navy on Saturday declared its missing submarine had sunk and cracked open,killing 53 crew members aboard,after finding items from the vessel over the past two days.\r\nMilitary chief Hadi… [+2957 chars]'},'name': 'Habs Eyes on the Prize'},'author': 'Matt Drake','title': 'It is time for Cole Caufield to get his shot - Habs Eyes on the Prize','description': 'The Canadiens may need to burn their final recall of the season so they can find out what they have.','url': 'https://www.habseyesontheprize.com/2021/4/24/22400671/cole-caufield-montreal-canadiens-lineup-calgary-flames-habs-power-play-takeaways','urlToImage': 'https://cdn.vox-cdn.com/thumbor/o47DFGBZJqh7sBXSjeqL75JHC5E=/0x196:2893x1711/fit-in/1200x630/cdn.vox-cdn.com/uploads/chorus_asset/file/19962182/1152080911.jpg.jpg','publishedAt': '2021-04-24T12:00:00Z','content': 'After yet another disappointing Montreal Canadiens loss against a Calgary Flames team chasing them in the standings no less Im at a loss. Frankly,I think the coaching staff must be as well,since th… [+2593 chars]'},'name': 'Montreal Gazette'},'author': 'Presse Canadienne','title': 'More than 350 people gathered at a place of worship in the Plateau,police say - Montreal Gazette','description': 'People left the synagogue when the service ended around 9:15,Montreal police say.','url': 'https://montrealgazette.com/news/local-news/more-than-350-people-gathered-at-a-place-of-worship-in-the-plateau-police-say','urlToImage': 'https://smartcdn.prod.postmedia.digital/montrealgazette/wp-content/uploads/2021/02/police_stk-w.jpg','publishedAt': '2021-04-24T11:49:28Z','content': 'Article content\r\nAbout 350 people gathered at a synagogue in the Plateau-Mont-Royal borough Friday evening,according to Montreal police.\r\nPolice say they received a 911 call around 8 p.m. from a cit… [+1258 chars]'},'name': '680 News'},'title': 'Peel health unit closes first businesses under new public health orders - 680 News','description': 'Peel Public Health has begun closing businesses with five or more cases of COVID-19 over the last 14 days under new powers aimed at limiting the spread of the virus in workplaces.','url': 'https://www.680news.com/2021/04/24/peel-health-unit-closes-first-businesses-under-new-public-health-orders/','urlToImage': 'https://www.680news.com/wp-content/blogs.dir/sites/2/2021/04/2021042218048-6081f44767766653252802fejpeg.jpg','publishedAt': '2021-04-24T11:40:08Z','content': 'Peel Public Health has ordered the partial closure of two Amazon fulfillment centres in Brampton and Bolton under its new Section 22 orders,after five or more cases of COVID-19 were detected in the … [+1956 chars]'},'name': 'Thompsoncitizen.net'},'author': '','title': 'China names Mars rover for traditional fire god - Thompson Citizen','description': 'BEIJING — China’s first Mars rover will be named Zhurong after a traditional fire god,the government announced Saturday.The rover is aboard the Tianwen-1 probe that arrived in Mars orbit on Feb. 24 . . .','url': 'https://www.thompsoncitizen.net/china-names-mars-rover-for-traditional-fire-god-1.24311092','urlToImage': 'https://images.glaciermedia.ca/polopoly_fs/1.24311093.1619261907!/fileImage/httpImage/image.jpg_gen/derivatives/facebookogimage_560_292/tksj101-1217-2020-015028-jpg.jpg','publishedAt': '2021-04-24T11:19:15Z','content': 'BEIJING Chinas first Mars rover will be named Zhurong after a traditional fire god,the government announced Saturday.\r\nThe rover is aboard the Tianwen-1 probe that arrived in Mars orbit on Feb. 24 a… [+1071 chars]'},'name': 'Forbes'},'author': 'David Phelan','title': 'iPad Pro 2021: The New Magic Keyboard’s Sly Little Detail - Forbes','description': 'The Magic Keyboard is one of Apple’s most brilliant successes. Now there’s a choice of colors for the new models,but one detail,borne out of Apple’s perfectionism,may be less welcome.','url': 'https://www.forbes.com/sites/davidphelan/2021/04/24/ipad-pro-2021-the-new-magic-keyboards-sly-little-secret-detail-price-release-date/','urlToImage': 'https://thumbor.forbes.com/thumbor/fit-in/1200x0/filters%3Aformat%28jpg%29/https%3A%2F%2Fspecials-images.forbesimg.com%2Fimageserve%2F607f25fd7c412073b2ee1c0b%2F0x0.jpg','publishedAt': '2021-04-24T11:00:00Z','content': 'iPad Pro and the new white Magic Keyboard.\r\nApple \r\nThe Magic Keyboard is Apples name for its super-comfortable,elegantly thought-out QWERTY,found on all the current MacBook Air and MacBook Pro lap… [+3882 chars]'},'name': 'SooToday.com'},'author': 'SooToday Staff','title': 'Good morning,Sault Ste. Marie! - SooToday','description': 'Give 100% today','url': 'https://www.sootoday.com/good-morning/good-morning-sault-ste-marie-3567086','urlToImage': 'https://www.vmcdn.ca/f/files/shared/good-morning/soo/2020-11-12-good-morning-sault-ste.-marie-(2).jpeg;w=1024;h=684;mode=crop','publishedAt': '2021-04-24T10:00:00Z','content': ''},'name': 'CNET'},'author': 'Patrick Holland','title': 'iPhone 12 in purple hands-on: Should you buy it or wait for iPhone 13? - CNET','description': "The iPhone 12 and 12 Mini are ready for spring. But you'll need to decide whether to open your wallet now or sit tight.",'url': 'https://www.cnet.com/news/iphone-12-in-purple-hands-on-should-you-buy-it-wait-for-iphone-13/','urlToImage': 'https://www.cnet.com/a/img/gvbz_XQx8Y0kMTTFTMPnYGo9Dgg=/1200x630/2021/04/22/79923b9c-039a-4d40-b661-1316715625d5/p1005637-1.jpg','publishedAt': '2021-04-24T09:37:03Z','content': "The iPhone 12 got a fresh new purple at Apple's Spring Loaded event.\r\nApple\r\nApple released a new color for the iPhone 12 and 12 Mini,and it's purple. It goes on sale Friday,but I got my hands on a… [+3276 chars]"},'title': "Canada's not trailing the world on climate action,environment minister insists - CBC.ca",'description': "Canada’s environment minister insists the federal government's commitment to reduce climate changing emissions by 40 to 45 per cent below 2005 levels over the next decade is just as ambitious as the higher targets announced this week by other western nations.",'url': 'https://www.cbc.ca/radio/thehouse/jonathan-wilkinson-climate-carbon-trudeau-1.5999748','urlToImage': 'https://i.cbc.ca/1.5956895.1616179199!/cumulusImage/httpImage/image.jpg_gen/derivatives/16x9_620/two-youth-climate-protesters-holding-a-sign.jpg','publishedAt': '2021-04-24T08:00:00Z','content': "Canada's environment minister insists the federal government's vow to reduce climate-changing emissions by 40 to 45 per cent below 2005 levels over the next decade is just as ambitious as the higher … [+5384 chars]"},'title': 'Ontario man speaks out after father has severe stroke from rare blood clot following AstraZeneca vaccine - CBC.ca','description': 'An Ontario man whose father suffered a severe stroke from a rare blood clot after receiving the AstraZeneca-Oxford COVID-19 vaccine is revealing new details about the condition for the first time in hopes of helping Canadians better understand the risk.','url': 'https://www.cbc.ca/news/health/astrazeneca-vaccine-canada-blood-clot-ontario-1.6000812','urlToImage': 'https://i.cbc.ca/1.6000844.1619222724!/cumulusImage/httpImage/image.jpg_gen/derivatives/16x9_620/downsview-arena-vaccination-clinic.jpg','content': "This is an excerpt from Second Opinion,a weekly roundup of health and medical science news emailed to\xa0subscribers every Saturday morning. If you haven't subscribed yet,you can do that by clicking\xa0h… [+8708 chars]"},{'source': {'id': 'cnn','name': 'CNN'},'author': 'Madeline Holcombe,CNN','title': "There may be more vaccines than people who want them by mid-May. Here's why that's a big problem. - CNN ",'description': 'By mid-May,the US will likely be coming up against a significant obstacle in the fight against the Covid-19 pandemic -- more doses of the vaccines than people who are willing to receive them,according to data that is worrying experts.','url': 'https://www.cnn.com/2021/04/24/health/us-coronavirus-saturday/index.html','urlToImage': 'https://cdn.cnn.com/cnnnext/dam/assets/210424005900-gardena-california-vaccination-0417-super-tease.jpg','publishedAt': '2021-04-24T06:09:00Z','content': '(CNN)By mid-May,a… [+6089 chars]'},'name': 'National Post'},'author': 'Anja Karadeglija','title': 'Can the NDP attract young voters in next election with #eattherich? - National Post','description': 'How much of the social media content is posted by Singh and how much is by his team depends on the platform','url': 'https://nationalpost.com/news/politics/can-the-ndp-attract-young-voters-in-next-election-with-eattherich','urlToImage': 'https://smartcdn.prod.postmedia.digital/nationalpost/wp-content/uploads/2021/04/Jagmeet-Singh.jpg','publishedAt': '2021-04-24T04:52:30Z','content': 'How much of the social media content is posted by Singh and how much is by his team depends on the platform \r\nAnja Karadeglija\r\nFederal NDP Leader Jagmeet Singh: "They\'ve been in power so many times … [+7917 chars]'},{'source': {'id': 'google-news','name': 'Google News'},'title': "Canada's 1st J&J shipment arriving next week - CityNews Toronto",'description': None,'url': 'https://news.google.com/__i/rss/rd/articles/CBMiK2h0dHBzOi8vd3d3LnlvdXR1YmUuY29tL3dhdGNoP3Y9ZjVSMFVIc'}]}

我可以访问某些键,例如“状态”和“总结果”,但不能访问“作者”或“内容”。我认为这与“来源”之前的方括号有关,但我不确定这是否是问题或如何解决。请帮我访问其他密钥?

jsonNews = json.loads(NewsResponse.text)
print(jsonNews['content'])

解决方法

您的jsonNews不是 JSON 内容(JSON 是字符串格式),您只有 python dictliststr


要访问某些content,您需要像这样访问每篇文章

for article in jsonNews['articles']:
    title = article.get('title')
    content = article.get('content')
    print(title)
    print(content)
    print("-" * 40)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...