将数组转换为JSON [英] Converting an array into JSON
本文介绍了将数组转换为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要引入一个csv doc并将其转换为JSON,到目前为止我已经能够将它转换为数组并从数组中我正在尝试构建一个JSON对象。
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.
下面是构建JSON的JavaScript,但它不在我需要的结构中,下面是所需结构的一个例子。
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
}
}
需要最终输出:
{
"key": "Sample 01",
"values": [
{
"label" : "Something" ,
"value" : 1
} ,
{
"label" : "Something" ,
"value" : 2
}
]
},
{
"key": "Sample 02",
"values": [
{
"label" : "Something" ,
"value" : 5
} ,
{
"label" : "Something" ,
"value" : 4
}
]
}
推荐答案
在将索引推送到最终/主要对象之前,需要声明值并将其推送到tmp变量
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
}
这篇关于将数组转换为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文