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
}
]
}
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
}
Simply use JSON.stringify()
to convert your array to json string
var jsonString = JSON.stringify(yourArray);
This script is a common way to convert an array to JSON in JavaScript.
I'm not a fan of answers like this, but this service in my opinion is good enough to warrant it. It can convert between various data formats including CSV, JSON, XML, HTML table, etc. It even offers variations in output structure for some of the formats.
- http://shancarter.github.io/mr-data-converter/
use this code and very simple develop for more two array
function getJSON(arrayID,arrayText) {
var JSON = "[";
//should arrayID length equal arrayText lenght and both against null
if (arrayID != null && arrayText != null && arrayID.length == arrayText.length) {
for (var i = 0; i < arrayID.length; i++) {
JSON += "{";
JSON += "text:'" + arrayText[i] + "',";
JSON += "id:'" + arrayID[i] + "'";
JSON += "},";
}
}
JSON += "]"
JSON = Function("return " + JSON + " ;");
return JSON();
}
and 3 array
function getJSON(arrayID, arrayText, arrayNumber) {
var JSON = "[";
if (arrayID != null && arrayText != null && arrayNumber!=null && Math.min(arrayNumber.length,arrayID.length)==arrayText.length) {
for (var i = 0; i < arrayID.length; i++) {
JSON += "{";
JSON += "text:'" + arrayText[i] + "',";
JSON += "id:'" + arrayID[i] + "',";
JSON += "number:'" + arrayNumber[i] + "'";
JSON += "},";
}
}
JSON += "]"
JSON = Function("return " + JSON + " ;");
return JSON();
}