2015-02-07 128 views
0

我正在使用自動喜歡圖片和關注人物的instagram機器人。我很難讓JSON正常工作。這裏是Python:Python - TypeError:字符串索引必須是整數 - Instagram機器人

 # Make a list of users who are currently being followed, or have been followed before 
    already_followed = [] 
    for tile in tiles['present']: 
     already_followed.append(tile['user_id']) 
    for tile in tiles['past']: 
     already_followed.append(tile['user_id']) 

這是我的JSON文件:

{ 
    "present": { 
    "user": {} 
    }, 
    "past": { 
    "user": {} 
    } 
} 

這是錯誤:

File "Instagram-bot.py", line 95, in <module> 
    already_followed.append(tile['user_id']) 
TypeError: string indices must be integers 

如果你們有什麼事,讓我知道!

+0

你有解決方案嗎? – 2015-02-07 05:04:59

回答

1

是,tile是字符串類型,即來自tiles['present']字典的關鍵字。

嘗試在代碼中打印變量tiletype。 例如

>>> a = 123 
>>> type(a) 
<type 'int'> 
>>> a = "123" 
>>> type(a) 
<type 'str'> 
>>> 

示例代碼:

tiles = { 
    "present": { 
    "user": {"user_id": 123} 
    }, 
    "past": { 
    "user": {"user_id": 456} 
    } 
} 

already_followed = [] 
for tile in tiles['present']: 
    already_followed.append(tiles['present'][tile]['user_id']) 

for tile in tiles['past']: 
     already_followed.append(tiles['past'][tile]['user_id']) 


print "already_followed:-", already_followed 

輸出:

[email protected]:~/Desktop/stackoverflow$ python 5.py 
already_followed:- [123, 456] 
相關問題