jqlang / jq

Command-line JSON processor
https://jqlang.github.io/jq/
Other
30.52k stars 1.58k forks source link

A new output format: Tcl dictionaries #685

Open dbohdan opened 9 years ago

dbohdan commented 9 years ago

I've implemented a function that produces Tcl dictionary output from jq (see man n tcl for an overview of the format). You will find it below.

If possible, I'd like to have it ship as part of jq (e.g., as @tcl). I've looked and all the existing export formats (@csv, @tsv, etc.) seem to be implemented in C rather than jq itself, so before I start working on a pull request I would like to ask: would be acceptable if I implemented @tcl as a call from f_format to a function stored in jq_builtins or should I avoid that and translate it to plain C?

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
        | gsub("{";"\\{")
        | gsub("}";"\\}")
    end;
. | totcl # Use example.
nicowilliams commented 9 years ago

Hey there, this is cool! Yes, perhaps format should be jq-coded, calling out to the C-coded form only for the C-coded formats. This should be easy to do, I think, and would be something like:

def format(fmt): if fmt == "@tcl" then ... else _format(fmt) end;
nicowilliams commented 9 years ago

We'll have to think about ways of making this something that can be delivered by modules.

dbohdan commented 9 years ago

@nicowilliams The ability to define new formats this way would be great!

I've updated the code to use gsub rather than split/join, which doesn't work for strings like "{something}".