Search code examples
kdb

Convert a csv string to a table in csv


If we have a file containing csv then we can read it using 0: say, we have a file x.csv on the disk then converting it to a table is easy as below

("SFJ";enlist",")0:`:/x.csv

But, how can we covert a csv string to table?
string:

"sym,px,vol
GG,10.2,100
AA,11.2,1000"

Expected output: table

sym px  vol
"GG"    10.2    100
"AA"    11.2    1000

Solution

  • If you needed to programmatically get to Eliot's s from one big string csv there are a few options depending on the format of the csv string.

    // \n delimited 
    s:` vs "sym,px,vol\nGG,10.2,100\nAA,11.2,1000"
    
    // if you know the row and col count. 
    s:3 3#"," vs "sym,px,vol,GG,10.2,100,AA,11.2,1000"
    
    // if you just know the col count
    s:"sym,px,vol,GG,10.2,100,AA,11.2,1000"
    f:{[str;noCol]
        str:"," vs str;   
        noRow:`long$(count str)%noCol;
        (noRow, noCol)#str
    }
    f[s;3] 
    

    All three output this ("sym,px,vol";"GG,10.2,100";"AA,11.2,1000")