Version 4 of JQ

Updated 2015-01-29 18:21:12 by dbohdan

JQ is short for Jamshed Qureshi


jq is also a command-line tool for *nix and Windows.

dbohdan 2015-01-29: You can use jq from Tcl, which can be faster than Tcllib JSON you only need a few values from a large JSON blob. It understands complex queries (called "filters") from .weather0.description to paths | map(tostring) | join("/") | unique to the one defined in the module below.

What follows is a small Tcl module to run jq. Note that ::jq::2dict is slower than ::json::json2dict (37 vs. 21 seconds to process a 10 MiB JSON file) and is only provided for a) the convenience of not having to import another package; b) the case when you want your JSON arrays to be converted to dicts with number keys. The latter allows you use dict get uniformly to access data convert from JSON.

# jq-0.2.tm
namespace eval jq {
    proc jq {filter data {options {-r}}} {
        exec -- jq {*}$options $filter << $data
    }
    proc 2dict {data} {
        jq {
            def totcl:
                if type == "array" then
                    # Convert array to object with keys 0, 1, 2... and process
                    # it as object.
                    [range(0;length) as $i
                    | {key: $i | tostring, value: .[$i]}]
                    | from_entries
                    | totcl
                elif type == "object" then
                    .
                    | to_entries
                    | map("{\(.key)} {\(.value | totcl)}")
                    | join(" ")
                else
                    tostring
                    | split("{") | join ("\\{")
                    | split("}") | join ("\\}")
                end;
            . | totcl
        } $data
    }
}

dbohdan: I hope Jamshed doesn't mind me using this page. If he objects I will create a separate page for jq the program.