TypeError:处理json文件时,字符串索引必须是整数

时间:2019-11-29 22:19:04

标签: python json

代码

client = gnewsclient.NewsClient(language='english', location='New Zealand', topic='Technology', max_results=5)
newsa = client.get_news()
newsb = json.dumps(newsa, indent=4, sort_keys=True)
newsc = newsb.replace('[', '')
newsc = newsc.replace(']', '')
print (newsc)
print (newsc["title"])

输出

Traceback (most recent call last):
  File "C:/Users/Paul/Documents/Python/J.A.R.V.I.S_001.py", line 87, in <module>
    jarvis(data)
  File "C:/Users/Paul/Documents/Python/J.A.R.V.I.S_001.py", line 81, in jarvis
    print (newsc["title"])
TypeError: string indices must be integers

    {
        "link": "https://news.google.com/__i/rss/rd/articles/CBMieGh0dHBzOi8vd3d3LnN0dWZmLmNvLm56L3Nwb3J0LzExNzgzNjMxNC9vbHltcGljcy1vcGVuaW5nLXNob290aW5nLXN0YXItc2hvdy1ob3BlLWZyb20tc2F0ZWxsaXRlLWxhdW5jaGluZy1pbi1uZXctemVhbGFuZNIBAA?oc=5",
        "media": null,
        "title": "Rocket Lab stands down rocket launch carrying Olympics opening 'shooting star' satellite - Stuff.co.nz"
    },
    {
        "link": "https://news.google.com/__i/rss/rd/articles/CBMiVGh0dHBzOi8vd3d3LnN0dWZmLmNvLm56L2J1c2luZXNzLzExNzgxMzEwOC9oZXJlLWFyZS10aGUtc2l4LWJlc3Qtc21hcnRwaG9uZXMtb2YtMjAxOdIBAA?oc=5",
        "media": null,
        "title": "Here are the six best smartphones of 2019 - Stuff.co.nz"
    },
    {
        "link": "https://news.google.com/__i/rss/rd/articles/CBMieGh0dHBzOi8vd3d3LnRlY2hyYWRhci5jb20vbnovbmV3cy9taWNyb3NvZnQtbWF5LWhhdmUtYS1jbGV2ZXItd2F5LXRvLWtlZXAtc3VyZmFjZS1uZW8tYW5kLW90aGVyLWxhcHRvcHMtZnJvbS1vdmVyaGVhdGluZ9IBfGh0dHBzOi8vd3d3LnRlY2hyYWRhci5jb20vbnovYW1wL25ld3MvbWljcm9zb2Z0LW1heS1oYXZlLWEtY2xldmVyLXdheS10by1rZWVwLXN1cmZhY2UtbmVvLWFuZC1vdGhlci1sYXB0b3BzLWZyb20tb3ZlcmhlYXRpbmc?oc=5",
        "media": null,
        "title": "Microsoft may have a clever way to keep Surface Neo \u2013 and other laptops \u2013 from overheating - TechRadar"
    },
    {
        "link": "https://news.google.com/__i/rss/rd/articles/CBMiTWh0dHBzOi8vaXRicmllZi5jby5uei9zdG9yeS92b2RhZm9uZS1uei1pbnZlc3RzLWluLWJvb3N0aW5nLWVuZXJneS1lZmZpY2llbmN50gFRaHR0cHM6Ly9pdGJyaWVmLmNvLm56L2FtcC9zdG9yeS92b2RhZm9uZS1uei1pbnZlc3RzLWluLWJvb3N0aW5nLWVuZXJneS1lZmZpY2llbmN5?oc=5",
        "media": null,
        "title": "Vodafone NZ invests in boosting energy efficiency - IT Brief New Zealand"
    },
    {
        "link": "https://news.google.com/__i/rss/rd/articles/CBMiQmh0dHBzOi8vY2hhbm5lbGxpZmUuY28ubnovc3RvcnkvaGFuZHMtb24tcmV2aWV3LXJpbmctZG9vci12aWV3LWNhbdIBRmh0dHBzOi8vY2hhbm5lbGxpZmUuY28ubnovYW1wL3N0b3J5L2hhbmRzLW9uLXJldmlldy1yaW5nLWRvb3Itdmlldy1jYW0?oc=5",
        "media": null,
        "title": "Hands-on review: Ring Door View Cam - ChannelLife New Zealand"
    }

1 个答案:

答案 0 :(得分:0)

您将newsc视为字典,但这是一个字符串。您的newsa是词典列表。不要尝试将其转换为字符串,然后从中删除方括号,以希望它将给yıu一个字典。像这样迭代:

for dic in newsa:
    print(dic['title'])

这应该为您提供列表中每本词典的title