1

我从这里有一个 http 查询:http ://www.omdbapi.com/?i=tt0084787&plot=full&language=1&r=json

我该如何拆分这个?

我可能会为所有变量,标题,年份,评级,流派,...语言,imdbRating,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]]
}
4

1 回答 1

3

首先,不要把你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)"
    }
}
于 2016-09-26T09:26:38.513 回答