【问题标题】:How to split a JSON file into separate files using Typescript如何使用 Typescript 将 JSON 文件拆分为单独的文件
【发布时间】:2021-07-03 11:29:41
【问题描述】:

我有一个包含数千个对象的大型 json 文件

{
    Desc: 'ABC',
    Arguments: [ 'Trace' ]
},
{
    Desc: 'XYZ',
    Arguments: [ 'Stack' ]
},

我想拆分这个 json 文件,让每个 json 文件包含一个文档,并用 value 命名它们:

ABC.json、XYZ.json、

例如,ABC.json 将包含:

{
    Desc: 'ABC',
    Arguments: [ 'Trace' ]
}

我想用打字稿来实现,有什么建议。

这是我不完整的代码。

const fs = require('fs');
const file = 'test.json';
const jsonData = mapEvents(getJSONFileData(file));

function getJSONFileData(filename) {
  return fs
    .readFileSync(filename, 'utf-8')
    .split('\n')
    .filter(Boolean)
    .map(JSON.parse);
}

function mapEvents(events) {
  return JSON.stringify(events);
}
const objects = JSON.parse(jsonData);
objects.filter(function () {
  return "Code" === "";
});

    for(const fname in objects){
        fileName = objects['Code']+'.json'
    }
  

【问题讨论】:

    标签: javascript node.js json typescript


    【解决方案1】:

    如果你的数据最初是一个数组,我认为你做的太多了。

    const fs = require('fs');
    const file = 'test.json';
    const data = JSON.parse(fs.readFileSync(file).toString());
    
    // loop over every entry
    data.forEach(record => {
        // save as record.Desc for the name. I'm not sure what you want to stringify
        // so I just put record there, perhaps you want record.Arguments
        fs.writeFileSync(`${record.Desc}.json`, JSON.stringify(record));
    });
    

    【讨论】:

    • 非常感谢您的回复,上面的代码在 forEach 不是函数时出现错误,因此已添加到 Object.keys(data) 中。您能告诉我如何添加具有值的文件名。当我运行代码文件时没有创建,获取带有单独对象的 json 数据作为响应而不是创建文件
    • 你能console.log(data);告诉我结构是什么样的?根据您的问题,它以[... 开头,所以这应该有效。
    • { Data: { Desc: "ABC", Arguments: [ 'Trace' ] } }, { Data: { Desc: "XYZ", Arguments: [ 'Stack' ] } } 整个对象数据进入单个,我需要将每个对象创建到具有相应值的单独文件中。
    • 让我再次说明我的要求,{ Data: { Desc: "ABC", Arguments: [ 'Trace' ] } }, { Data: { Desc: "XYZ", Arguments: [ 'Stack' ] } } 预期输出是 ABC.json 应该有 { Data: { Desc: "ABC", Arguments: [ 'Trace' ] } } 和 XYZ.json 应该有 { Data: { Desc: "XYZ", Arguments: [ 'Stack' ] } }
    • 我认为这不是有效的 JSON,也许您可​​以这样做:const data = JSON.parse('[' + fs.readFileSync(file).toString() + ']');
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-07
    • 2015-05-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多