简体   繁体   English

JSON字符串索引必须是整数

[英]JSON String Indices Must Be Integers

There are a number of questions with this subject, but most seem to be people forgetting to call json.loads . 关于这个主题有很多问题,但大多数人似乎都忘了打电话给json.loads

Here is my example: 这是我的例子:

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'])

The call to print fails with the error: 打印调用因错误而失败:

TypeError: string indices must be integers TypeError:字符串索引必须是整数

How can I resolve this? 我该如何解决这个问题?

What you are currently printing is the key for the article dict, and not the article's title itself. 您当前打印的内容是文章字典的关键,而不是文章标题本身。 If you print article in your example, it will print the keys 如果您在示例中打印文章,它将打印键

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

To print the article's title, iterate on the items within the dict: 要打印文章的标题,请迭代dict中的项目:

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

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

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