首先,不要把你package require
的 s 放在程序中。那是不雅的。其次,不要忘记http::cleanup
令牌,否则你会得到一些泄露的资源(只是内存,但它会随着时间的推移而增加)。
json2dict
可以使用 json 包的命令将 JSON 响应转换为 Tcl 字典。(这个包是 tcllib 的一部分,以防你没有安装它。)一旦你有了字典,用dict with
它来打开它作为单独的变量;对于您的情况,这是最简单的方法。
这是结果,也有很多评论。
# package requires go at the top *BY CONVENTION* so they're easy to see
package require http
package require json
bind pub - !imdb imdb
proc imdb { nick uhost hand chan text} {
# Parse what the user said; this is shorter, especially when working with more variables
lassign [split $text] id
# Talk to the web service and parse the result
# NOTE that this doesn't handle errors such as a non-existent ID...
set tok [http::geturl "http://www.omdbapi.com/?i=$id&plot=short&r=json"]
set data [json::json2dict [http::data $tok]]
http::cleanup $tok
# Work with the results
dict with data { # <<<< Magical!
puthelp "Movie: $Title ($Year)"
}
}