Search code examples
jsoncsvdata-conversion

How can I convert csv to json file in that form?


I have a Csv file like this sample:

0   -8,396  13,414  -35,891 39,22489124
1   -8,789  12,768  -35,891 39,09516883
2   -9,136  12,768  -35,891 39,17463722
3   -9,614  12,768  -35,891 39,2888623
4   -9,614  12,397  -36,282 39,52844709
5   -9,614  12,397  -36,282 39,52844709

I need to convert it to a JSON file in that form:

{"0": [-12.770680147058824, 1.846047794117647, -54.265625, 55.77863587895704], 
"1": [-18.388229927007298, 6.5360401459854014, -52.65647810218978, 56.156491225545878], 
"2": [-20.042738970588236, 12.849264705882353, -46.678308823529413, 52.399231898471129], 
"3": [-38.242244525547449, 15.836222627737227, -40.48357664233577, 57.897972254845804], 
"4": [-33.016879562043798, 6.3001824817518246, -38.179288321167881, 50.867127813832226]}

Do you have any idéa how can I do that?


Solution

  • try to use this tool (play a little with parameters) or this javascript code:

    csv.split(/\n/).map(l=>{[n,...a]=l.split(/ +/),out[n]=a.map(x=>+x.replace(',','.'))})
    

    let out={}, csv= `0   -8,396  13,414  -35,891 39,22489124
    1   -8,789  12,768  -35,891 39,09516883
    2   -9,136  12,768  -35,891 39,17463722
    3   -9,614  12,768  -35,891 39,2888623
    4   -9,614  12,397  -36,282 39,52844709
    5   -9,614  12,397  -36,282 39,52844709`;
    
    csv.split(/\n/).map(l=> {[n,...a]=l.split(/ +/),out[n]=a.map(x=>+x.replace(',','.'))});
    
    console.log(JSON.stringify(out,0,4));

    To download this as file use this