用 Python 编写 API 代码、条形码查找"argument of type 'int' is not iterable"



我正在写一个代码以从UPC/条形码数据库API中提取,我正在尝试制作它,因此,如果您在拉的JSON数据中找到一件东西('":1'),然后打印出项目的名称。我有错误:

    Traceback (most recent call last):
    File "/Users/thomasceluzza/Documents/UPC API Grabber/api.py", line 13, in <module> 
    if '1' in importedJSON['total']:
    TypeError: argument of type 'int' is not iterable

来自完整代码

    import urllib2
    import json
    import sys
    while '1' == '1':
        apikey = 'c2c33e74ea9ee432fd1cdbf546a3132c'
        upc = raw_input("Scan your barcode: ")
        url = 'https://api.upcitemdb.com/prod/trial/lookup?upc=' + str(upc)
        json_obj = urllib2.urlopen(url)
    importedJSON = json.load(json_obj)
    if importedJSON['code'] == 'OK':
        if '1' in importedJSON['total']:
            print ' '
            print 'The product you scanned is ',
            for name in importedJSON['items']:
                sys.stdout.write(name['title'])
            print ' '
            print ' '
        else:
            print ' '
            print 'NOT IN DATABASE'
            print ' '
    else:
        print ' '
        print 'Invalid UPC/EAN code. Please scan again.'
        print ' '

谢谢!

看起来像total存储int值,而不是str。因此,大概您想测试:

if importedJSON['total'] == 1:

或测试任何非零total

if importedJSON['total']:

您的 json.load呼叫执行类型转换,而您的行为就像没有。即使没有,if '1' in importedJSON['total']:也只有在totallist或一个拼写的数字,并且由于某种原因"1""21"是可以接受的,但是"2"不可接受。in毕竟用于遏制检查,而不是平等检查。

最新更新