kdb

Saving kdb+/q table into JSON


As we know we can serialize q table by utilizing .j.j namespace.

However, upon using either save or set to write a serialized q table into appropriate .json file, there is an issue of missing , after every row. When running save (`$":", (getenv `HOME), "/test.json") in q we get:

{"dir":"1","recursion":"False"}
{"dir":"2","recursion":"True"}

As you can see there's a missing , which VSCode picks up. However if you run (`$":", (getenv `HOME), "/test.json") set (.j.j .testTable) , we get following JSON output:

NULLNULLNULLNULL[{"dir":"1","recursion":"False"}, {"dir":"2","recursion":"True"}]

But we get the NULL here however, rows seem to be separated.

Is there a convenient way to save q tables into .json? I looked through every topic and had a look at the official docs and even RapidJSON git repository to try and install that package thinking it may be quicker but also more up-to-date. My question is, are any of the above appropriate or is there a better way to save into .json so that any other software can read it efficiently including Python?


Solution

  • Use 0: (https://code.kx.com/q/ref/file-text/#save-text):

    q)t:flip`dir`recursion!(1 2f;01b)
    q)`:test.json 0: enlist .j.j t
    `:test.json
    

    This writes test.json:

    $ cat test.json
    [{"dir":1,"recursion":false},
     {"dir":2,"recursion":true}]
    

    which can be read back into kdb+:

    q)t~.j.k raze read0`:test.json
    1b