日语 CSV 到 JSON 解析错误

Japanese CSV to JSON parse Error

我想将我的 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?

我并没有真正修改你代码的相关部分,但似乎对我有用。 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 服务器 headers 设置为:

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

如果您无法更改您的服务器设置,这里有一个 work-around 可以让您在根本不更改服务器设置的情况下执行此操作:我建议使用 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);
            }
        });
    });