无法使用json文件

时间:2019-09-12 09:00:12

标签: python json

迭代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

1 个答案:

答案 0 :(得分:0)

在字典中未找到键且未提供默认键时,字典get method将返回None

所以您要么需要

    正如EdChumif所说,
  • 检查a中的每个obj是否实际上都具有该键

  • 检查您是否正确运行了解码的json对象的结构

  • get函数提供一个默认的空Iter。

在没有看到您正在使用的文件的样本的情况下,我们无法为您提供更具体的答案。