首页 > 解决方案 > 在 NodeJS 中将 JSON 转换为 TXT 格式

问题描述

我们使用一个JSON名为 gsjson 的便捷模块将 Google Sheet 数据转换为 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

标签: javascripthtmljsonnode.jsaws-lambda

解决方案


您不想这样做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) {
  // ...

推荐阅读