JSON 字符串索引必须是整数

JSON String Indices Must Be Integers

这个主题有很多问题,但大多数似乎是人们忘记打电话给 json.loads

这是我的例子:

import json

json_input = '{ "ar": { "articles": { "12345": {"title": "first title" } , "67890": {"title": "another title" } } } } '

data = json.loads(json_input)

for article in data['ar']['articles']:
    print(article['title'])

打印调用失败并出现错误:

TypeError: string indices must be integers

我该如何解决这个问题?

您当前正在打印的是文章字典的关键字,而不是文章标题本身。如果您在示例中打印文章,它将打印键

In [6]: for article in data['ar']['articles']:
        print(article)
   ...:     
67890
12345

要打印文章标题,请迭代字典中的项目:

In [1]: import json

In [2]: json_input = '{ "ar": { "articles": { "12345": {"title": "first title" } , "67890": {"title": "another title" } } } } '

In [3]: data = json.loads(json_input)

In [4]: for article in data['ar']['articles'].values():
   ...:     print(article['title'])
   ...:     
another title
first title