【问题标题】:'NoneType' object is not iterable using json file'NoneType' 对象不可使用 json 文件进行迭代
【发布时间】:2019-09-12 09:00:12
【问题描述】:

我在迭代 Json 文件时遇到此错误 'NoneType' object is not iterable

我的代码:

import nltk
import json
from nltk import word_tokenize
with open('full_format_recipes.json', 'r') as myfile:
data=myfile.read()
obj = json.loads(data)
result=[]
for a in obj:
    for b in a.get("ingredients"):
        print(type(b))
        text = word_tokenize(b)
        res = nltk.pos_tag(text)
        res = [t for t in res if isinstance(t[1],list) not in ["NN", 
         "NNS","NNP", "NNPS"]]
        print(res)
        result.append(res)

错误:

for b in a.get("ingredients"): TypeError: 'NoneType' object is not iterable

【问题讨论】:

  • 所以很可能没有关键的“成分”,因此出现错误,您检查了吗?
  • 你能在这里解释/粘贴文件内容吗?

标签: python json


【解决方案1】:

当在字典中找不到键且未给出默认值时,字典 get method 返回 None

所以你要么需要

  • 检查,正如 EdChumif 所说,obj 中的每个 a 是否真的有那个键

  • 检查您是否正确地遍历解码后的 json 对象的结构

  • 提供一个空的可迭代对象作为get 函数的默认值。

如果没有看到您正在使用的文件的样本,我们无法给您更具体的答案。

【讨论】:

  • 我会发给你json文件
  • 但是我把我的 json 文件发给你
  • @ShahWajahat 我们并不需要完整的文件,但我们需要一个小样本来查看它的结构。如果您内部有敏感/私人信息,您可以通过 had 更改该信息,并通过编辑问题本身将该示例添加到您的问题中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-02-08
  • 2020-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-01
相关资源
最近更新 更多