You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Windows与Linux环境下脚本输出文件格式差异问题求助

问题解决:跨平台换行符导致的JSON格式异常

问题根源

Windows系统的文本文件换行符是\r\n(回车+换行),而Linux是\n。你目前的脚本只按\n分割行,导致Windows下读取的每行末尾残留了\r字符,这个字符会被渲染成换行,最终破坏JSON字段的格式。

修复方案

修改脚本里的行分割逻辑和内容处理步骤,兼容两种换行符并清理多余的控制字符:

修改后的完整代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Schmutz</title>
</head>
<body>
    <input type="file" name="schmutz" id="schmutz">
</body>
<script>
    document.getElementById('schmutz').onchange = function(){
    var file = this.files[0];

    var reader = new FileReader();
    reader.onload = function(progressEvent){
    console.log(this.result);

    var text = "";
    // 兼容Windows(\r\n)和Linux(\n)的换行符
    var lines = this.result.split(/\r?\n/);
    for(var line = 0; line < lines.length; line++){
      // 跳过空行(处理文件末尾可能的空行)
      if(!lines[line].trim()) continue;
      if(line != 0){
          text += "\n";
      }
        // 用trim()清理首尾的空白字符(包括\r和空格)
        text += "{\"tradeable-code\": \""+lines[line].replace("#spawnitem ","").trim()+"\",\"base-purchase-price\": \"-1\",\"base-sell-price\": \"-1\",\"delta-price\": \"-1.0\",\"can-be-purchased\": \"false\"},";
    }

    text = text.replace(/,*$/, '');
    console.log(text);
    download(text);
    };
    reader.readAsText(file);

    };

    function download(data, filename = "schmutz.json", type = "json") {
        var file = new Blob([data], {type: type});
        if (window.navigator.msSaveOrOpenBlob) // IE10+
            window.navigator.msSaveOrOpenBlob(file, filename);
        else { // Others
            var a = document.createElement("a"),
                    url = URL.createObjectURL(file);
            a.href = url;
            a.download = filename;
            document.body.appendChild(a);
            a.click();
            setTimeout(function() {
                document.body.removeChild(a);
                window.URL.revokeObjectURL(url);  
            }, 0);
        }
    }
</script>
</html>

关键修改点

  1. 行分割逻辑:把split('\n')改成split(/\r?\n/),正则表达式\r?\n会匹配\n(Linux)或\r\n(Windows)两种换行符,确保跨平台分割正确。
  2. 清理行内容:在拼接字符串时,对每行内容调用trim()方法,去除首尾的\r、空格等空白字符,避免多余字符破坏JSON格式。
  3. 跳过空行:增加了if(!lines[line].trim()) continue;判断,处理文件末尾可能存在的空行,避免生成无效的JSON条目。

内容的提问来源于stack exchange,提问作者Spyr0

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 17:45:38