【问题标题】:Convert JSON into TXT format in NodeJS在 NodeJS 中将 JSON 转换为 TXT 格式
【发布时间】:2019-02-16 20:15:56
【问题描述】:

我们使用名为 gsjson 的便捷 JSON 模块将 Google 表格数据转换为 JSON。我需要以 TXT 格式获取作为 URL 列表列出的工作表。

我尝试更改扩展名,但它只是输出为 JSON 格式。如何将其转换为纯文本列表(不包括标题),逐行列出 URL?

// Create JSON file from Google Sheet and place in tmp
gsjson({
    spreadsheetId: sheetid ,
    credentials: 'mycreds.json'
})
.then(function(result) {
    result = JSON.stringify(result);
    fs.writeFile("/tmp/" + company +".json", result, 'utf-8', function (err) {
        if (err) console.log('Google Sheet written to tmp JSON - FAILED'); // an error occurred
        else     console.log('Google Sheet written to tmp JSON - SUCCESS');           // successful response
});

当前 JSON 输出

[{"url":"https://example.com"},{"url":"https://examples.com"}]

所需的 TXT 输出

https://example.com https://examples.com

【问题讨论】:

    标签: javascript html json node.js aws-lambda


    【解决方案1】:

    您不想stringify 它,这会将其转换为 JSON 格式,这对于您要查找的内容没有意义。如果您只需要数组中每个项目的url 属性,请使用.map 提取每个属性,然后通过换行符加入:

    // ...
    .then(function(result) {
      const textToWrite = result.map(({ url }) => url).join('\n');
      fs.writeFile("/tmp/" + company +".json", textToWrite, 'utf-8', function (err) {
      // ...
    

    【讨论】:

    • 太好了,谢谢。快到了,但输出为 https://example.comhttps://examples.com 而不是 2 行
    • 呃,真的吗?我有点怀疑,你确定不只是你的编辑?你确实包括了.join('\n'),对吧?我想你可以试试\r\n,Windows 环境有时更喜欢这种方式
    • 你说得对,当我在 Windows 中打开它时,它会像这样出现。但在 S3 上,它输出良好 s3-eu-west-1.amazonaws.com/githubgists/jsontotext.txt。一切都很好,打勾
    猜你喜欢
    • 2020-11-09
    • 2021-12-11
    • 1970-01-01
    • 2018-05-27
    • 1970-01-01
    • 1970-01-01
    • 2015-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多