Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
-7
rated 0 times [  0] [ 7]  / answers: 1 / hits: 27893  / 11 Years ago, wed, october 9, 2013, 12:00:00

I need to bring in a csv doc and convert it to JSON, so far I have been able to convert it to an array and from the array I'm trying to build a JSON object.



Below is the JavaScript that builds the JSON, but its not in the structure I need, underneath is an example of the structure required.



var jsonObj = []; //declare object

for (var i=1;i<csvAsArray.length;i++) {
jsonObj.push({key: csvAsArray[i][0]}); //key

for (var l=1;l<csvAsArray[0].length;l++) {
jsonObj.push({label: csvAsArray[0][l], values: csvAsArray[i][l]}); //label + value respectively
}
}


Final output required:



{
key: Sample 01,
values: [
{
label : Something ,
value : 1
} ,
{
label : Something ,
value : 2
}
]
},
{
key: Sample 02,
values: [
{
label : Something ,
value : 5
} ,
{
label : Something ,
value : 4
}
]
}

More From » jquery

 Answers
1

You need to declare the values and push that onto a tmp variable before pushing that index onto the final/main object



var tmp_values, jsonObj = []; //declare object

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

[#75129] Tuesday, October 8, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cristopherh

Total Points: 402
Total Questions: 117
Total Answers: 84

Location: Monaco
Member since Fri, Sep 24, 2021
3 Years ago
;