Aquarius24
Aquarius24

Reputation: 1866

JSON object from csv

my csv file is as follows:

NAME,AGE
"John","23"
"BOB","24"

When executing below code, I am getting {} as alert instead of JSON object. My intended output should be JSON file in below format:

{
    "items": [
        {
            "NAME": "John",
            "AGE": " 23"
        },
        {
            "NAME": "BOB",
            "AGE": "24"
        },
    ]
}

CODE:

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
        <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
        <script type="text/javascript" src="json.js"></script>
<script type="text/javascript" src="json2.js"></script>
<script type="text/javascript">
  var lines = {};
$(document).ready(function() {
    $.ajax({
        type: "GET",
        url: "data.csv",
        dataType: "csv",
        success: function(data) {processData(data);}
     });
});

function processData(allText) {
    var allTextLines = allText.split(/\r\n|\n/);
    var headers = allTextLines[0].split(',');


    for (var i=1; i<allTextLines.length; i++) {
        var data = allTextLines[i].split(',');
        if (data.length == headers.length) {

            var tarr = [];
            for (var j=0; j<headers.length; j++) {
                tarr.push(headers[j]+":"+data[j]);
            }
            lines.push(tarr);
        }
    }
    alert(lines);
}


var val = JSON.stringify(lines);

alert(val);
</script>
</head>
<body>

</body>
</html>

Upvotes: 1

Views: 1441

Answers (3)

agershun
agershun

Reputation: 4107

You can do all these operations in one line with Alasql library. The following script can load the data file from server, parse it and put the result to array of JSON objects:

<script src="alasql.min.js"></script>
<script>
    alasql('SELECT NAME, AGE FROM CSV("items.csv",{headers:true})',[],function(res){
        var data = {items:res};
    });
</script>

Upvotes: 0

Milan V.
Milan V.

Reputation: 697

/*NAME,AGE"John","23""BOB","24"*/
var mvJSON = {};
var myCSV;
var myJSON_str = '{"items":[]}';
var resJSON_str = "";

//*** Edit
$.get("yourcsvfilepath.csv",function(data){
    // coopy file content of csv to variable
    myCSV = data;
    console.clear();processData(myCSV); 
});
//*** Done Edit





function processData(allText) {

    var items = allText.split(',');
    var keys = [items[0],items[1]];
    var items_str = "";

        for(var i = 2; i< items.length;i = i+2){
            items_str += (i==2) ? '{"'+keys[0]+'":'+items[i]+',"'+keys[1]+'":'+items[i+1]+'}' : ',{"'+keys[0]+'":'+items[i]+',"'+keys[1]+'":'+items[i+1]+'}';     
        }

        items_str = items_str.replace("\n","");
        items_str = items_str.replace("\r","");    
        resJSON_str = myJSON_str.substring(0,myJSON_str.length-2)+items_str+myJSON_str.substring(myJSON_str.length-2,myJSON_str.length);
        alert(resJSON_str);

}

Upvotes: 0

MaxK
MaxK

Reputation: 434

You are trying to push a single string value to an array, rather than key value pairs to an object. so rather than tarr being an array, make it an object. as such, you need to use assign by index rather than using push. The other issue is that lines is never made to contain items, which should be your array.

$(document).ready(function() {
    $.ajax({
        type: "GET",
        url: "data.csv",
        dataType: "csv",
        success: function(data) {processData(data);}
    });
});

function processData(allText) {
    var lines = {};
    var items = [];
    var allTextLines = allText.split(/\r\n|\n/);
    var headers = allTextLines[0].split(',');


    for (var i=1; i<allTextLines.length; i++) {
        var data = allTextLines[i].split(',');
        if (data.length == headers.length) {

            var tarr = {};
            for (var j=0; j<headers.length; j++) {
                tarr[headers[j]] = data[j];
            }
            items.push(tarr);
        }
    }
    lines.items = items;
    alert(lines);
}

edit: Rereading it, if you want actual javascript object, use what i put above. if you want an array of lines of text, do what you were doing, but replace the objects with arrays

Upvotes: 1

Related Questions