4

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?

fao
  • 251
  • 4
  • 16

7 Answers7

3

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

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
  • 1
    Can you give some extra hint? – fao Jul 28 '16 at 12:38
  • 1
    Directions: You may have to change your commas to periods in your input depending on your locale settings. 1. Paste your data into the input area. 2. Input Options - Field Separator is Space and Uncheck First Row is Header 3. In Step 4 template- Set Top to be {lb}{br}, Repeating Section to be "{f1}" : [ {f2}, {f3}, {f4}, {f5} ] and Bottom to be {br}{rb} then press Convert Csv to JSON via Template. – dataman Jul 29 '16 at 01:03
2

Here is a solution using jq

reduce (
    split("\n")[]           # split string into lines
  | split("\t")             # split into columns
  | select(length>0)        # eliminate blanks
  | map(gsub(",";"."))      # change decimal character
) as $r (
  {}
; .[$r[0]] = $r[1:]         # build requested result 
)

If filter.jq contains this filter and data contains tab-separated data

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

the sample data then

$ jq -M -R -r -s -f filter.jq data | \
  sed -e ':a' -e 'N' -e '$!ba' \
      -e 's/",\n   /",/g' \
      -e 's/\[\n   /\[/g' \
      -e 's/\n  \]/\]/g'

produces

{
  "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"]
}

Note the sed at the end is only to present more compact JSON for this Stack Overflow example.

jq170727
  • 13,159
  • 3
  • 46
  • 56
2

In javascript

index.html

file as input

<input type="file" id="csvFileInput" onchange="handleFiles(this.files)" accept=".csv"> 

app.js

Converting csv data to json

function handleFiles(files) {
   if (window.FileReader) {
    getText(files[0]);
   } else {
    alert('FileReader are not supported in this browser.');
  }
}


function getText(fileToRead) {
    var reader = new FileReader(); 
    reader.readAsText(fileToRead);
    reader.onload = loadHandler;
    reader.onerror = errorHandler;
}

 function loadHandler(event) {
    var csv = event.target.result;
    process(csv);
 }

 function process(csv) {

     // Newline split
     var lines = csv.split("\n");

     result = [];

     var headers = lines[0].split(",");

     for (var i = 1; i < lines.length - 1; i++) {

        var obj = {};

        //Comma split
        var currentline = lines[i].split(",");

        for (var j = 0; j < headers.length; j++) {
           obj[headers[j]] = currentline[j];
        }

        result.push(obj);

    }

    // OUTPUT
    console.log(result);

}

function errorHandler(evt) {
   if (evt.target.error.name == "NotReadableError") {
       alert("Canno't read file !");
   }
}
Manav Kothari
  • 1,149
  • 1
  • 6
  • 7
0

It's tough to answer this without knowing which language you're using but the general idea should be the same for most. I would take the approach of reading the CSV file in line by line something like:

    JSONObject jsn = new JSONObject()
    for(line in csvfile){
        List lst = new ArrayList();
        String[] temp = line.split(","); //as it should be comma separated
        for(int i=1;i<temp.len;++i){
            lst.add(temp[i]);
        }
        jsn.put(temp[0], list);
    }

This is just a sudo code example but you should get the point.

0

You can use this CSV to JSON Converter to do what you want.

Click on the Examples and then choose Headerless Indexed. That will load an example based on this problem. Then click on Convert. The main setting that drives this conversion is an Output Type of Dictionary Array.

PS: Your input is a bit inconsistent in terms of the delimiters (spaces ranging from 1 to 3 characters). I'm guessing it was a result of copy pasting it here and that the original file has tabs as delimiters.

Disclaimer: I built this tool.

Partho
  • 138
  • 1
  • 11
0

Assuming you don't want a programming solution:

CsvCruncher takes CSV as a SQL table and let's you do a SELECT, exporting the result as CSV or JSON. github.com/OndraZizka/csv-cruncher

crunch -in <inputFile>.csv -out <outputFile>.json --json -sql "SELECT * FROM <inputFile>"

It doesn't give exactly the format you need, but then you could employ a little bit of JavaScript to change the data structure.

Ondra Žižka
  • 43,948
  • 41
  • 217
  • 277
0

Window's users could use the Powershell 3.0 console for converting INPUTFILE.csv to OUTPUTFILE.json by using the below command.

c:\> $jsonData = import-csv .\INPUTFILE.csv | ConvertTo-Json -depth 100 
                                            | Out-File .\OUTPUTFILE.json
SridharKritha
  • 8,481
  • 2
  • 52
  • 43