我正在处理一些CSV数据。现在,CSV有一个名为'characteristic'的列,它是三种类型之一,还有一个名为'value'的列,它包含特征的数值。 我想更改数据的结构,以便列本身就是特征,并且值直接落在这些列之下。 以下是表格的屏幕截图:
我手动改变了一些例子。我需要更改的实际表是数千行,所以我希望我能以某种方式以编程方式执行此操作。
我需要重构的原因是我需要将CSV转换为JSON,JSON需要如下所示:
[
{
"country":"afghanistan",
"iso3":"afg",
"first_indicator":3,
"second_indicator":5,
"third_indicator":3
},
{
"country":"united states",
"iso3":"usa",
"first_indicator":8,
"second_indicator":6,
"third_indicator":7
},
{
"country":"china",
"iso3":"chn",
"first_indicator":6,
"second_indicator":0.7,
"third_indicator":2
}
]
那么 - 有没有什么方法可以像现在这样使用我的CSV(第一次截图),并将其转换为我想要的JSON,而不是手动完成所有操作? 我做了很多搜索,我想也许我只是不知道要搜索什么。理想情况下,我会使用javascript,但欢迎任何建议。 谢谢。
答案 0 :(得分:1)
我为你做了JSFiddle,这样的事情应该是你想要的。
的JavaScript
function Country(name, short){
this["country"] = name;
this["iso3"] = short;
}
function getCountryByName(name) {
for(var i = 0; i < countries.length; i++){
var country = countries[i];
if(country["country"] == name){
return country;
}
}
return null;
}
var csv = "country,shortname,characteristics,value\nafghanistan,afg,first_characteristic,3\nunited states,usa,first_characteristic,8\nchina,chn,first_characteristic,6\nafghanistan,afg,second_characteristic,5\nunited states,usa,second_characteristic,6\nchina,chn,second_characteristic,0.7\nafghanistan,afg,third_characteristic,3\nunited states,usa,third_characteristic,7\nchina,chn,third_characteristic,2"
var rows = csv.split("\n");
var countries = [];
if(rows.length > 0){
var header = rows[0];
var columns = header.split(",");
var countryIndex = columns.indexOf("country");
var shortnameIndex = columns.indexOf("shortname");
var characteristicsIndex = columns.indexOf("characteristics");
var valueIndex = columns.indexOf("value");
for(var i = 1; i < rows.length; i++) {
var row = rows[i];
var columns = row.split(",");
var name = columns[countryIndex];
var short = columns[shortnameIndex];
var characteristic = columns[characteristicsIndex];
var value = columns[valueIndex];
var country = getCountryByName(name);
if(!country){
country = new Country(name, short);
countries.push(country);
}
country[characteristic.replace("characteristic", "indicator")] = +value;
}
}
console.log(countries);
console.log(JSON.stringify(countries));
最后一行的输出是:
[{"country":"afghanistan","iso3":"afg","first_indicator":"3","second_indicator":"5","third_indicator":"3"},
{"country":"united states","iso3":"usa","first_indicator":"8","second_indicator":"6","third_indicator":"7"},
{"country":"china","iso3":"chn","first_indicator":"6","second_indicator":"0.7","third_indicator":"2"}]
答案 1 :(得分:0)
我的建议是先将CSV转换为JSON。您可以使用online tool。 当您拥有JSON时,您可以编写Javascript代码来修改所需格式的JSON。