1

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>

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

0
/*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);

}

1 Comment

my csv file is in .csv format and not a string like in this code. how can i give path of csv here rather than giving string
0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.