我正在写一个代码以从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']:
也只有在total
是list
或一个拼写的数字,并且由于某种原因"1"
和"21"
是可以接受的,但是"2"
不可接受。in
毕竟用于遏制检查,而不是平等检查。