javascript 使用 jquery 将 CSV 转换为 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18355354/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
CSV to JSON using jquery
提问by Aquarius24
I have file in csv format:
我有 csv 格式的文件:
info,value
"off to home","now"
"off to office","tomorrow"
I want json out of this using jquery but couldnt find any help.Isnt it possible to use jquery for this?
我想使用 jquery 将 json 排除在外,但找不到任何帮助。是否可以为此使用 jquery?
My intended output is :
我的预期输出是:
{
"items": [
{
"info": "off to home",
"value": "now"
},
{
"info": "off to office",
"value": "tomorrow"
},
]
}
PFB the code which i implemented. but it is not working
PFB 我实现的代码。但它不起作用
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="csvjson.js"></script>
<script>
$.ajax("data.csv", {
success: function(data) {
var jsonobject = csvjson.csv2json(data);
alert(jsonobject);
},
error: function() {
alert("error")
}
});
</script>
</head>
<body>
</body>
</html>
回答by Evan Plaice
Using jquery-csv, specifically the toObjects()
method
使用jquery-csv,特别是toObjects()
方法
$.ajax({
url: "data.csv",
async: false,
success: function (csvd) {
var items = $.csv.toObjects(csvd);
var jsonobject = JSON.stringify(items);
alert(jsonobject);
},
dataType: "text",
complete: function () {
// call a function on complete
}
});
Note: You'll need to import the jquery-csv library for this to work.
注意:您需要导入 jquery-csv 库才能使其工作。
What this does is transform the CSV data into an array of objects.
这样做是将 CSV 数据转换为对象数组。
Since the first line contains headers, jquery-csv knows to use those as the keys.
由于第一行包含标题,jquery-csv 知道将它们用作键。
From there the data is transformed to JSON using stringify()
.
从那里,数据使用 .json 转换为 JSON stringify()
。
If you need a wrapper object, just create one and attach the data to it.
如果您需要一个包装器对象,只需创建一个并将数据附加到它。
var wrapper = {};
wrapper.items = items;
alert(wrapper);
Disclaimer: I'm the author of jquery-csv
免责声明:我是 jquery-csv 的作者
回答by Shoaib Ijaz
Useful link, I have found. Maybe help someone.
有用的链接,我找到了。也许帮助某人。
http://jsfiddle.net/sturtevant/AZFvQ/
http://jsfiddle.net/sturtevant/AZFvQ/
function CSVToArray(strData, strDelimiter) {
// Check to see if the delimiter is defined. If not,
// then default to comma.
strDelimiter = (strDelimiter || ",");
// Create a regular expression to parse the CSV values.
var objPattern = new RegExp((
// Delimiters.
"(\" + strDelimiter + "|\r?\n|\r|^)" +
// Quoted fields.
"(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +
// Standard fields.
"([^\"\" + strDelimiter + "\r\n]*))"), "gi");
// Create an array to hold our data. Give the array
// a default empty first row.
var arrData = [[]];
// Create an array to hold our individual pattern
// matching groups.
var arrMatches = null;
// Keep looping over the regular expression matches
// until we can no longer find a match.
while (arrMatches = objPattern.exec(strData)) {
// Get the delimiter that was found.
var strMatchedDelimiter = arrMatches[1];
// Check to see if the given delimiter has a length
// (is not the start of string) and if it matches
// field delimiter. If id does not, then we know
// that this delimiter is a row delimiter.
if (strMatchedDelimiter.length && (strMatchedDelimiter != strDelimiter)) {
// Since we have reached a new row of data,
// add an empty row to our data array.
arrData.push([]);
}
// Now that we have our delimiter out of the way,
// let's check to see which kind of value we
// captured (quoted or unquoted).
if (arrMatches[2]) {
// We found a quoted value. When we capture
// this value, unescape any double quotes.
var strMatchedValue = arrMatches[2].replace(
new RegExp("\"\"", "g"), "\"");
} else {
// We found a non-quoted value.
var strMatchedValue = arrMatches[3];
}
// Now that we have our value string, let's add
// it to the data array.
arrData[arrData.length - 1].push(strMatchedValue);
}
// Return the parsed data.
return (arrData);
}
function CSV2JSON(csv) {
var array = CSVToArray(csv);
var objArray = [];
for (var i = 1; i < array.length; i++) {
objArray[i - 1] = {};
for (var k = 0; k < array[0].length && k < array[i].length; k++) {
var key = array[0][k];
objArray[i - 1][key] = array[i][k]
}
}
var json = JSON.stringify(objArray);
var str = json.replace(/},/g, "},\r\n");
return str;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
回答by agershun
You can use Alasqllibrary. Alasql can load the data file from server, parse it and put the result to array of JSON objects.
您可以使用Alasql库。Alasql 可以从服务器加载数据文件,解析它并将结果放入 JSON 对象数组。
This is the code:
这是代码:
<script src="alasql.min.js"></script>
<script>
alasql('SELECT * FROM CSV("items.csv",{headers:true})',[],function(res){
var data = {items:res};
});
</script>
If you want to modify data (for example, use only one column or filter), you can do it "on the fly". Alasql understands the headers and use them for SELECT statement:
如果您想修改数据(例如,仅使用一列或过滤器),您可以“即时”进行。Alasql 理解标题并将它们用于 SELECT 语句:
alasql('SELECT info FROM CSV("items.csv") WHERE value = "now"',[],function(res){
console.log(res);
});
回答by Kariem Muhammed
I think jquery csvplugin will be helpful to convert your CSV to an array, then you can use jquery json.
BTW, you can use $.get()
to read your CSV file from server.
我认为jquery csv插件将有助于将您的 CSV 转换为数组,然后您可以使用jquery json。顺便说一句,您可以使用$.get()
从服务器读取您的 CSV 文件。