dongtazu3080 2017-07-21 19:06 采纳率: 100%
浏览 338
已采纳

.txt写入.json文件批处理或php文件需要

i need and search for a result to convert my .txt file to a .json file with that format:

{
"id":"12777475756802056",
"typ":"Solo",
"match":
    {
        "rank":"1",
        "playeruserid":"165496871657",
        "playername":"Example Name",
        "kills":"8",
        "points":"224000",
        "killer":"empty", // while firstplace
        "weapon":"empty" // while firstplace
    },
    {
        "rank":"2",
        "playeruserid":"654987654984",
        "playername":"Example Name 2",
        "kills":"4",
        "points":"168000",
        "killer":"Example Name",
        "weapon":"Shotgun"
    }
    ... another players here.
}

and my .txt file looks so, yep really bad... with so many spaces and all in one line...: https://pastebin.com/FP0C9BCj

i try this batch to remove the many spaces:

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION 
SET "sourcedir=D:\Users\Raphael\Desktop"
SET "destdir=D:\Users\Raphael\Desktop"
SET "filename1=%sourcedir%\matchreport.txt"
SET "outfile=%destdir%\outfile.txt"
(
FOR /f "usebackqdelims=" %%a IN ("%filename1%") DO (
 SET "line=%%a"
 SET "line=!line:?=!"
 SET "line=!line:/=-!"
 SET "line=!line::=!"
 SET "line=!line: =;!"
 ECHO !line!
)
)>"%outfile%"

GOTO :EOF

and idk now why can convert this now to a json file, while all informations on one line pro player, and the json format is now:

{"1. 5605****11014 Cl***ma  205000 + 19000 ( 8) = 224000"}

and sorry this is my first try to convert a txt to a json file have u any idea to convert this? :/

  • 写回答

3条回答 默认 最新

  • dongpa5277 2017-07-21 20:39
    关注

    This almost works. (Requires PowerShell 3.0 or newer, so, Windows 8 or newer.) It's a Batch + PowerShell polyglot. Save it with a .bat extension.

    <# : batch portion
    @echo off & setlocal
    
    set "file=test.txt"
    
    powershell -noprofile "iex (${%~f0} | out-string)"
    exit /b
    
    : end batch / begin powershell #>
    
    function Parse-Fields() {
        add-type -as Microsoft.VisualBasic
        $parser = new-object Microsoft.VisualBasic.FileIO.TextFieldParser($env:file)
    
        $parser.TextFieldType = "FixedWidth"
        $parser.TrimWhiteSpace = $true
        $parser.FieldWidths = @(7, 21, 25, 6, 9, 4, 12, 26, -1)
    
        while (!$parser.EndOfData) {
            try {
                $parser.ReadFields() -join "," -replace "[\(\+\)\.=]" | ?{ $_ -match "\d" }
            }
            catch {}
        }
        $parser.Close()
    }
    
    $header = "ID","GameUserId","Name","Rank","Kills","Score","Total","Killer","Weapon"
    Parse-Fields | ConvertFrom-Csv -Header $header | ConvertTo-Json
    

    Output:

    [
        {
            "ID":  "1",
            "GameUserId":  "5605****11014",
            "Name":  "Cl***ma",
            "Rank":  "205000",
            "Kills":  "19000",
            "Score":  "8",
            "Total":  "224000",
            "Killer":  "",
            "Weapon":  "m4"
        },
        {
            "ID":  "2",
            "GameUserId":  "238444****020",
            "Name":  "Ap*******ift",
            "Rank":  "172403",
            "Kills":  "11550",
            "Score":  "3",
            "Total":  "183953",
            "Killer":  "Cl***ma",
            "Weapon":  "m4"
        },
        {
            "ID":  "3",
            "GameUserId":  "92******9515",
            "Name":  "Sw****UK",
            "Rank":  "156259",
            "Kills":  "14900",
            "Score":  "6",
            "Total":  "171159",
            "Killer":  "Ap*******ift",
            "Weapon":  "m4"
        },
        {
            "ID":  "4",
            "GameUserId":  "6583833***132",
            "Name":  "Moc********kap",
            "Rank":  "144805",
            "Kills":  "2000",
            "Score":  "1",
            "Total":  "146805",
            "Killer":  "Cl***ma",
            "Weapon":  "shotgun"
        },
        {
            "ID":  "5",
            "GameUserId":  "621***7360388",
            "Name":  "Ol***r***",
            "Rank":  "135920",
            "Kills":  "6200",
            "Score":  "3",
            "Total":  "142120",
            "Killer":  "Ap*******ift",
            "Weapon":  "m4"
        },
        {
            "ID":  "6",
            "GameUserId":  "189661****980",
            "Name":  "Op*********gon",
            "Rank":  "128661",
            "Kills":  "0",
            "Score":  "0",
            "Total":  "128661",
            "Killer":  "Sw****UK",
            "Weapon":  "m4"
        },
        {
            "ID":  "7",
            "GameUserId":  "6408****79452",
            "Name":  "M********nner",
            "Rank":  "122523",
            "Kills":  "3500",
            "Score":  "2",
            "Total":  "126023",
            "Killer":  "Sw****UK",
            "Weapon":  "shotgun"
        },
        {
            "ID":  "8",
            "GameUserId":  "59060***2163",
            "Name":  "A***g",
            "Rank":  "117207",
            "Kills":  "0",
            "Score":  "0",
            "Total":  "117207",
            "Killer":  "Ap*******ift",
            "Weapon":  "ak"
        },
        {
            "ID":  "9",
            "GameUserId":  "831467****599",
            "Name":  "*********ngstar",
            "Rank":  "112517",
            "Kills":  "0",
            "Score":  "0",
            "Total":  "112517",
            "Killer":  "Ol***r***",
            "Weapon":  "shotgun"
        },
        {
            "ID":  "10",
            "GameUserId":  "34542****7961",
            "Name":  "********Really",
            "Rank":  "108322",
            "Kills":  "5000",
            "Score":  "3",
            "Total":  "113322",
            "Killer":  "[Toxic Gas]",
            "Weapon":  null
        },
        {
            "ID":  "11",
            "GameUserId":  "904****58750",
            "Name":  "******tch",
            "Rank":  "104528",
            "Kills":  "3500",
            "Score":  "2",
            "Total":  "108028",
            "Killer":  "Sw****UK",
            "Weapon":  "shotgun"
        }
    ]
    

    It probably won't take much to massage it to fit your requirements. I prefer objectifying data over scraping as flat text. The script first treats the data as a fixed-width CSV file. Once objectified as CSV data, it's the converted to JSON. If no one else suggests a better answer, maybe you can use this as a skeleton to build your project.


    As an alternative, here's a Batch + JScript polyglot that's a bit more efficient than the PowerShell method, although it's longer. It doesn't suffer the overhead required by the TextFieldParser() class, and JScript is just faster than PowerShell in general. As a bonus, it should work with earlier versions of Windows, as long as IE version 9 or newer is installed (Vista SP2 I think?). If you're more comfortable with JavaScript, you might prefer this one.

    @if (@CodeSection == @Batch) @then
    @echo off & setlocal
    
    set "file=test.txt"
    
    cscript /nologo /e:JScript "%~f0" < "%file%"
    exit /b
    
    @end // end Batch / begin JScript
    
    var stdin = WSH.CreateObject('Scripting.FileSystemObject').GetStandardStream(0),
        file = stdin.ReadAll(),
        htmlfile = WSH.CreateObject('htmlfile'),
        csvfields = {"ID": 7, "GameUserId": 21, "Name": 25, "Rank": 6, "Kills": 9,
            "Score": 4, "Total": 12, "Killer": 26, "Weapon": null};
    
    String.prototype.clean = function() {
        var val = this.replace(/[\(\)\.\+=]/g, '').replace(/^\s+|\s+$/g, '');
        return /^\d+$/.test(val) ? val * 1 : val;
    }
    
    htmlfile.write('<meta http-equiv="x-ua-compatible" content="IE=9" />');
    var JSON = htmlfile.parentWindow.JSON,
        lines = obj = new htmlfile.parentWindow.Array();
    htmlfile.close();
    
    lines = file.split(/?
    /g);
    lines.splice(0,4);
    for (var i=0; i<lines.length; i++) {
        for (var field in csvfields) {
            if (!obj[i]) obj.push({});
            obj[i][field] = csvfields[field] ?
                lines[i].substring(0, csvfields[field]).clean() : lines[i].clean();
            lines[i] = lines[i].substring(csvfields[field]);
        }
    }
    
    WSH.Echo(JSON.stringify(obj, null, '    '));
    

    Output is similar, just with integer values unquoted.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥50 swiftui @query 报错
  • ¥50 怎么解决刷卡或扫码后,点击软件输入框,win10屏幕键盘不会自动弹出的问题
  • ¥15 如何使用arcgispro的训练深度模型,发现water和nowater精度为0?(相关搜索:深度学习)
  • ¥20 matlab作业不太懂呀有问题能给个代码吗
  • ¥15 自制电路图为何无法驱动ESP01S?
  • ¥15 前端加access数据库
  • ¥15 ARCGIS 多值提取到点 ERROR 999999
  • ¥15 mysql异常断电, [MY-011971] [InnoDB]
  • ¥15 uni.onBluetoothDeviceFound熄屏不运行
  • ¥15 求PHDA糖尿病并发症数据集,有偿