0

I am trying to get a file from user, convert it into an array and need to develop a histogram. For developing a histogram, I need to have that data in json format. Though there are enough example to convert an array into json hard coded, but I am not able to find a single example to convert it dynamically on real time basis. Here is my code:

<input type="file" name="F1" id="F1" size="80">
<input type="button" value="Read" name="B1" id="B1" onclick="execFile()">

function execFile() {
    // main function to open, parse, and then render
    var myfile=document.getElementById("F1")
    arr = readCSV(myfile.value);
    // parse csv line by line
    for (var i=0;i<arr.length;i++) {
        arr[i] = parseLineCSV(arr[i]);
    }
    for (var i=0;i<arr.length;i++) {
        document.write(arr[i]);
    } 
}

So, I need to pass an array arr to convert to json. I found this code from another user but it seems not working for me.

for(var i=1;i<arr.length;i++) {
    var tmp_values = [];
    alert(arr.length);
    for (var l=1;l<arr[0].length;l++) { 
        alert(arr[0].length);
        tmp_values.push({label: arr[0][l], value: arr[i][l]}); //label + value respectively
        alert("2");
    }
    jsonObj.push({key: arr[i][0], values: tmp_values}); //key
    alert("3");
}

I am doing some mistake as I am able to get only arr.length and alert 3.. I am doing some mistake with push function, but cant figure out what. So , please help

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
user3050590
  • 1,656
  • 4
  • 21
  • 40
  • I agree with @vp_arth What does `arr` contains? `Array` or something else? – Madhu Apr 16 '14 at 07:06
  • 1
    Do you mean JS object rather than JSON? JSON is easy: JSON.stringify(arr). If you mean JS object, then you need to give a bit more specification as to what you want the object to look like. – Amadan Apr 16 '14 at 07:10
  • It looks like you want create an array of objects, not JSON. JSON is a textual, language-independent data exchange format. And it doesn't look like you want generate text. – Felix Kling Apr 16 '14 at 07:21

1 Answers1

0

I found this solution, normally this should do the trick.

var myJsonString = JSON.stringify(yourArray);

see here for more :

Convert array to JSON

Community
  • 1
  • 1
Nick
  • 30
  • 6