【问题标题】:Undefined JSON usage in Python 2.7Python 2.7 中未定义的 JSON 用法
【发布时间】:2017-03-19 18:57:02
【问题描述】:

我在理解这个 python 代码的语法时遇到了一些问题。有问题的代码是一个简单的 Telegram 聊天机器人,它通过从 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__'

而如果我保持该代码部分不变并保留 JSON,则代码可以完美运行。

编辑:这是机器人将从数据中提取的示例:

{"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"}}]}

【问题讨论】:

  • 请修正格式
  • 已修复,感谢您的关注。
  • 代码是否完整? URL在哪里定义?无论如何,更新的类型似乎是无。因此使用 getitem -> [] 会导致异常?
  • 代码已经完成,还添加了拉取数据的示例。
  • 您确定每次发出请求都会收到正确的响应吗?

标签: python json python-2.7 chatbot


【解决方案1】:

正如@mic4ael 指出的那样,命令:mechanize.read() 返回一个带有JSONstr 对象,例如'{"updates": []}' 然后必须使用json.loads 将其转换为 Python 对象(dict) 我错误地认为 `mechanize.read()' 数据将是一个 python 对象。

【讨论】:

    猜你喜欢
    • 2017-08-02
    • 2018-07-31
    • 2015-04-16
    • 1970-01-01
    • 1970-01-01
    • 2021-11-20
    • 2017-01-23
    • 1970-01-01
    • 2012-10-22
    相关资源
    最近更新 更多