Search code examples
jsontcleggdrop

how to format json to output


I have this json link, https://predb.ovh/api/v1/?q=@name%20IfIca.Icssssy

The returned JSON is

{
    "status": "success",
    "message": "",
    "data": {
        "rowCount": 0,
        "rows": [],
        "offset": 0,
        "reqCount": 20,
        "total": 0,
        "time": 0.003080273
    }
}

The output status and message working. When rowCount is also in the output, I get an error:

Tcl error : can't read "rowCount": no such variable

bind pub "-|-" !search pub:test
proc pub:test { nick host handle channel arg } {

    set name [lindex $arg 0]
    set tok [http::geturl "https://predb.ovh/api/v1/?q=@name%20$name"]

    set aadata [json::json2dict [http::data $tok]]
    http::cleanup $tok  
    dict with aadata {
        putnow "PRIVMSG $channel :status $status"
        putnow "PRIVMSG $channel :rowCount $rowCount"
    }

}

Solution

  • The problem is that the key rowCount is not directly under the aadata dict, it resides in a sub-dict.

    If you want to use dict with you'll have to do

    dict with aadata {
        putnow "PRIVMSG $channel :status $status"
        dict with data {
            putnow "PRIVMSG $channel :rowCount $rowCount"
        }
    }
    

    or, simpler:

    putnow "PRIVMSG $channel :status [dict get $aadata status]"
    putnow "PRIVMSG $channel :rowCount [dict get $aadata data rowCount]"