【问题标题】:How to show list of certain items from JSON如何从 JSON 中显示某些项目的列表
【发布时间】:2020-02-07 08:02:58
【问题描述】:

我一直在尝试显示 JSON 文件中的 cmets 列表。 我不断收到此错误:

Traceback(最近一次调用最后一次): 文件“JsonExtraction.py”,第 7 行,在 在 len(data) 中发表评论: TypeError: 'int' 对象不可迭代

我的代码如下所示:

import json

data = []
for line in open('rating_company_small.json', 'r'):
    data.append(json.loads(line))

for comment in len(data):
    print(comment['comment'])

谁能解释这个错误?

【问题讨论】:

  • 你能在你的 rating_company_small.json 中分享一个示例数据(数据格式)吗?

标签: python json file


【解决方案1】:

您应该迭代 data,它是一个对象列表,而不是 len(data),它是一个数字并且不可迭代!

for comment in data:
    # Do stuff

len(data)返回data的长度,即列表中的项目数。)

【讨论】:

    【解决方案2】:

    您错误地迭代您的列表。

    选项 1:

    for index in range(0, len(data)):
        print(data[index])
    

    选项 2:

    for comment in data:
        print(comment['comment'])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-14
      • 1970-01-01
      • 2012-11-02
      • 2013-05-28
      相关资源
      最近更新 更多