我有一个http查询从这里:http://www.omdbapi.com/?i=tt0084787&plot=full&language=1&r=json
我怎么分割这个?
我可以为所有变量,标题,年份,评级,类型,…语言,imdating, imdbVotes等。
bind pub - !imdb imdb
proc imdb { nick uhost hand chan text} {
package require http
set id [lindex [split $text] 0];
set url "http://www.omdbapi.com/?i=$id&plot=short&r=json"
set data [::http::data [::http::geturl $url]]
}
首先,不要将您的package require
放在程序中。这是不雅的。其次,不要忘记http::cleanup
令牌,否则你会得到一些泄漏的资源(只是内存,但随着时间的推移,它会增加)。
JSON响应可以通过JSON包中的json2dict
命令转换为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)"
}
}