日语CSV到JSON解析错误

时间:2018-03-21 13:31:04

标签: javascript csv papaparse

我想将我的CSV文件解析为JSON文件。我已经解析了它,但它没有得到日文字符。

我正在使用Papa Parser将CSV解析为JSON。

这是我的代码: -

Papa.parse("http://localhost:3000/readdata.csv", {
    download: true,
    header: true, 
    worker: true,
    encoding: 'Shift-JIS',
      console.log(row);
    },
    complete: function() {
      console.log("All done!");
    }
});

答案: -

{��s����: "0", ��s��(��): "�����", ��s��(����): "���{��s", �x�X����: "79", �x�X��(��): "���-", …}

解析有效但不能正常编码。

还有其他解决方案可以将日文CSV(大文件)解析为JSON吗?

1 个答案:

答案 0 :(得分:4)

我没有真正修改代码的相关部分,但似乎对我有用。 Firefox 58在这里。

<html>
<head>
    <script src="papaparse.js"></script>
</head>
<body>
    <script>
    function openFile(event) {
        var input = event.target;
        Papa.parse(input.files[0], {
            download: true,
            header: true, 
            worker: true,
            encoding: 'Shift-JIS',
            complete: function(results) {
                console.log("All done!", results.data);
            }
        });
    }
    </script>
    <input type='file' onchange='openFile(event)'><br>
</body>
</html>

不幸的是,当我从URL检索文件时,这对我来说不起作用,即使我将Web服务器标头设置为:

Content-Type: text/plain; charset=shift_jis

Content-Type: text/plain; charset=shift-jis

更新:实际上,这看起来效果很好。如果您在浏览器缓存中有旧版本,则可能会遇到问题。

以下是演示:https://blog.qiqitori.com/stackexchange/papaparse/papaparse-sjis-from-url.html

$ curl -I https://blog.qiqitori.com/stackexchange/papaparse/readdata-charset-sjis.csv
HTTP/1.1 200 OK
Date: Thu, 22 Mar 2018 05:23:49 GMT
Server: Apache/2.4.25 (Debian)
Last-Modified: Wed, 21 Mar 2018 15:48:17 GMT
ETag: "15a-567ee1ea9847f"
Accept-Ranges: bytes
Content-Length: 346
Vary: Accept-Encoding
Content-Type: text/plain; charset=shift_jis

如果您无法更改服务器设置,可以使用以下方法来完成此操作而不更改服务器设置:我建议使用XMLHttpRequest将CSV加载到变量中,并强制执行编码为Shift-JIS

function load(url, callback) {
    var Xhr = new XMLHttpRequest();
    Xhr.onreadystatechange = function () {
        if (Xhr.readyState === 4 && Xhr.status === 200)
            callback(Xhr.responseText);
    };
    Xhr.open("GET", url, true);
    Xhr.overrideMimeType('text/plain; charset=Shift_JIS');
    Xhr.send();
}

load("http://.../readdata.csv", function (contents) {
        Papa.parse(contents, {
//          download: true,
            header: true, 
            worker: true,
//          encoding: 'Shift-JIS',
            complete: function(results) {
                console.log("All done!", results.data);
            }
        });
    });