【发布时间】:2019-04-18 13:57:27
【问题描述】:
我在尝试使用 JS 将客户端提供的 CSV 转换为 JSON 数据时遇到映射问题。 CSV 中的一列包含地址数据,其中包含逗号。我尝试更改分隔符,但由于某种原因,当我阅读 CSV JS 时会忽略设置的分隔符并将它们转换为逗号。这意味着将数据转换为 JSON 时的映射不正确。下面的代码和输出:-
JS :-
$(document).ready(function() {
$.ajax({
type: "GET",
url: "result.csv",
dataType: "text",
success: function(data) { $("body").append(csvJSON(data));}
});
});
function csvJSON(csv){
var lines=csv.split("\n");
var result = [];
var headers=lines[0].split(",");
for(var i=1;i<lines.length;i++){
var obj = {};
var currentline=lines[i].split(",");
for(var j=0;j<headers.length;j++){
obj[headers[j]] = currentline[j];
}
result.push(obj);
}
return JSON.stringify(result);
}
CSV 数据:-
"type","geometry__type","geometry__coordinates__001","geometry__coordinates__002","properties__name","properties__address","properties__address2","properties__city","properties__state","properties__postal","properties__country","properties__phone","properties__phoneFormatted","properties__email","properties__web"
"Stockist","Point",-110.788,43.4705,"Whitechapel Ltd","Box 11719, 1135 Maple Way","Jackson,","Wyoming","WY",83002,"US",13077399478,"+1 307 739-9478","whitechapel@wyoming.com","www.whitechapel-ltd.com"
"Stockist","Point",103.82705,1.30637,"Thrive Design & Trading","19, Tanglin Road, #03-35","Tanglin Shopping Centre","Singapore",,247909,"Singapore","65-67357333","65-67357333","francis@thrive-products.com.sg",
当前结果:-
{
"type":"Stockist",
"geometry__type":"Point",
"geometry__coordinates__001":"-110.788",
"geometry__coordinates__002":"43.4705",
"properties__name":"Whitechapel Ltd",
"properties__address":"\"Box 11719",
"properties__address2":" 1135 Maple Way\"",
"properties__city":"\"Jackson",
"properties__state":"\"",
"properties__postal":"Wyoming",
"properties__country":"WY",
"properties__phone":"83002",
"properties__phoneFormatted":"US",
"properties__email":"13077399478",
"properties__web\r":"+1 307 739-9478"
},
期望的结果:-
{
"type":"Stockist",
"geometry__type":"Point",
"geometry__coordinates__001":"-110.788",
"geometry__coordinates__002":"43.4705",
"properties__name":"Whitechapel Ltd",
"properties__address":"Box 11719, 1135 Maple Way",
"properties__address2":"Jackson,",
"properties__city":"Wyoming",
"properties__state":"WY",
"properties__postal":"83002",
"properties__country":"US",
"properties__phone":"13077399478",
"properties__phoneFormatted":"+1 307 739-9478",
"properties__email":"whitechapel@wyoming.com",
"properties__web":"www.whitechapel-ltd.com"
},
【问题讨论】:
-
要在哪个字段中去掉逗号
-
"我尝试更改分隔符,但由于某种原因,当我阅读 CSV JS 时忽略了设置的分隔符并将它们转换为逗号。"...上面的代码始终使用逗号。你能告诉我们一个你做了什么的例子吗?你的陈述并不完全有意义......代码不会“忽略”事情,它只是按照它的指示做,所以也许你犯了一些小错误。另请显示将转换为上述 JSON 的源 CSV 数据。这样会清楚很多。通常,CSV 会在字段周围加上双引号,这样您就可以知道哪些位是分隔符,哪些是内容
-
我不想删除逗号,你可以看到我用逗号分割 CSV 数据,这会导致数据与正确的标题不匹配。更改分隔符似乎不起作用,JS总是以逗号作为分隔符读取文件。
-
result.csv 的内容是什么
-
你能发一个简单的样本数据(csv)吗?
标签: javascript jquery arrays json csv