将 .txt 文件转换为 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39803874/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:38:53  来源:igfitidea点击:

Convert .txt file to JSON

jsonapitype-conversion

提问by

I want to convert a fairly unorganized and unstructured textfile to JSON format. I want to be able to use the city ID information. Is there anyway I can convert this to JSON?

我想将一个相当无组织和非结构化的文本文件转换为 JSON 格式。我希望能够使用城市 ID 信息。无论如何我可以将其转换为JSON吗?

UPDATE:I also found this solution after a while. Very simple way to get the JSON of any tab separated text file.

更新:一段时间后我也找到了这个解决方案。获取任何制表符分隔文本文件的 JSON 的非常简单的方法。

https://shancarter.github.io/mr-data-converter/

https://shancarter.github.io/mr-data-converter/

采纳答案by Dmitry Bubnenkov

You can try to use tsv2jsonthis tool can reads a tsv file from stdin and writes a json file to stdout.

您可以尝试使用tsv2json这个工具可以从 stdin 读取 tsv 文件并将 json 文件写入 stdout。

It's distributed in source file, to compile it you need to download D compilerand then run dmd tsv2json.d.

它分布在源文件中,要编译它,您需要下载D 编译器,然后运行dmd tsv2json.d.

If you have more complex task there is another tool named tsv-utils

如果您有更复杂的任务,还有另一个名为tsv-utils 的工具

回答by asissuthar

TSV to JSON in nodejs

nodejs 中的 TSV 到 JSON

var file_name = 'city_list.txt';

var readline = require('readline');
var fs = require('fs');

var lineReader = readline.createInterface({
    input: fs.createReadStream(file_name)
});

var isHeader = false;
var columnNames = [];

function parseLine(line) {
    return line.trim().split('\t')
}

function createRowObject(values) {
    var rowObject = {};

    columnNames.forEach((value,index) => {
        rowObject[value] = values[index];
    });

    return rowObject;
}

var json = {};
json[file_name] = [];

lineReader.on('line', function (line) {
    if(!isHeader) {
        columnNames = parseLine(line);
        isHeader = true;
    } else {
        json[file_name].push(createRowObject(parseLine(line)));
    }
});

lineReader.on('close', function () {
    fs.writeFileSync(file_name + '.json', JSON.stringify(json,null,2));
});