python
  • json
  • 2016-12-28 7 views -1 likes 
    -1

    UPC/barcodeデータベースAPIからプルするコードを作成しています。プルされたJSONデータ( '"total":1')で1つのものを見つけて、アイテムの名前を表示します。私はエラーを取得する:完全なコードPythonでのAPIコードの作成、バーコード検索、「int型の引数が反復可能ではありません」

    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 ' ' 
    

    おかげでから来て、どの

    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 
    

    答えて

    1

    totalのように見えますが、strではなく、intの値が格納されています。だから、おそらくあなたは、テストしたい:

    if importedJSON['total'] == 1: 
    

    またはゼロ以外のtotalをテストする:

    if importedJSON['total']: 
    

    あなたjson.load呼び出しが型変換を行い、それがなかったようにあなたが演技しています。たとえそれでもなかったとしても、totallist、または何らかの理由で"1""21"のいずれかであった場合には、if '1' in importedJSON['total']:は意味をなさないが、"2"は受け入れられませんでした。 inは、封じ込めチェックのためのものであり、等価性チェックではありません。

    関連する問題