6

我有 csv 格式的文件:

info,value
"off to home","now"
"off to office","tomorrow"

我想要使​​用 jquery 的 json,但找不到任何帮助。是否可以为此使用 jquery?

我的预期输出是:

 {
        "items": [
            {
                "info": "off to home",
                "value": "now"
            },
            {
                "info": "off to office",
                "value": "tomorrow"
            },

        ]
    }

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>
4

4 回答 4

7

使用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 
    }
});

注意:您需要导入 jquery-csv 库才能使其正常工作。

它的作用是将 CSV 数据转换为对象数组。

由于第一行包含标题,jquery-csv 知道将它们用作键。

从那里数据使用stringify().

如果您需要一个包装对象,只需创建一个并将数据附加到它。

var wrapper = {};
wrapper.items = items;
alert(wrapper);

免责声明:我是 jquery-csv 的作者

于 2016-01-21T13:12:17.680 回答
4

有用的链接,我发现了。也许可以帮助某人。

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>

于 2015-09-11T09:59:53.810 回答
1

您可以使用Alasql库。Alasql 可以从服务器加载数据文件,解析它并将结果放入 JSON 对象数组。

这是代码:

<script src="alasql.min.js"></script>
<script>
    alasql('SELECT * FROM CSV("items.csv",{headers:true})',[],function(res){
        var data = {items:res};
    });
</script>

如果您想修改数据(例如,只使用一列或过滤器),您可以“即时”进行。Alasql 理解标题并将它们用于 SELECT 语句:

alasql('SELECT info FROM CSV("items.csv") WHERE value = "now"',[],function(res){
     console.log(res);
});
于 2014-12-17T08:38:51.803 回答
0

我认为jquery csv插件将有助于将您的 CSV 转换为数组,然后您可以使用jquery json。顺便说一句,您可以使用$.get()从服务器读取 CSV 文件。

于 2013-08-21T11:03:43.860 回答