Python 2.7中未定义的JSON用法

Python 2.7中未定义的JSON用法,python,json,python-2.7,chatbot,Python,Json,Python 2.7,Chatbot,我在理解这段python代码的语法时遇到了一些问题。所讨论的代码是一个简单的电报聊天机器人,它通过从https门获取更新来工作 URL = "https://api.telegram.org/bot{}/".format(TOKEN) def get_url(url): response = mechanize.urlopen(url) content = response.read() return content def get_json_from_url(url

我在理解这段python代码的语法时遇到了一些问题。所讨论的代码是一个简单的电报聊天机器人,它通过从https门获取更新来工作

URL = "https://api.telegram.org/bot{}/".format(TOKEN)

def get_url(url):
    response = mechanize.urlopen(url)
    content = response.read()
    return content

def get_json_from_url(url):
    content = get_url(url)
    js = json.loads(content)
    return js

def get_updates(offset=None):
    url = URL + "getUpdates"
    if offset:
        url += "?offset={}".format(offset)
    js = get_json_from_url(url)
    return js

def get_last_update_id(updates):
    update_ids = []
    for update in updates["result"]:
        update_ids.append(int(update["update_id"]))
    return max(update_ids)

def echo_all(updates):
    for update in updates["result"]:
        text = update["message"]["text"]
        chat = update["message"]["chat"]["id"]
        send_message(text, chat)

def get_last_chat_id_and_text(updates):
    num_updates = len(updates["result"])
    last_update = num_updates - 1
    text = updates["result"][last_update]["message"]["text"]
    chat_id = updates["result"][last_update]["message"]["chat"]["id"]
    return (text, chat_id)
据我所知,JSON在这种情况下几乎没有用处,因为mechanize返回一个UTF-8 str。 但是,一跑,

def main():
    last_update_id = None
    while True:
        updates = get_updates(last_update_id)
        if len(updates["result"]) > 0:
            last_update_id = get_last_update_id(updates) + 1
            #echo_all(updates)
            send_stdmessage(updates)
我得到以下错误:

Traceback (most recent call last):
File "PreAlpha.py", line 70, in <module>
main()
File "PreAlpha.py", line 62, in main
if len(updates["result"]) > 0:
TypeError: 'NoneType' object has no attribute '__getitem__'

正如@mic4ael所指出的,命令:
mechanize.read()
返回一个带有
JSON
str
对象,例如“{”updates:[]}”,然后必须使用
JSON.loads将其转换为Python对象(
dict

我错误地认为'mechanize.read()'数据将是python对象。

请修复格式它已修复,谢谢您的提醒。代码是否完整?URL在哪里定义?无论如何,更新的类型似乎没有。因此,使用getitem->[]会导致异常?代码现在已完成,并且还添加了一个拉取数据示例。您确定每次发出请求时都会收到正确的响应吗?
{"ok":true,"result":[{"update_id":130999147,"message":
{"message_id":24,"from":
{"id":346850522,"first_name":"XXX","last_name":"XXX"},"chat":
{"id":346850522,"first_name":"XXX","last_name":"XXX",
"type":"private"},"date":1489950868,"text":"Hello"}}]}