javascript - 在 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
解决方案
您不想这样做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) {
// ...
推荐阅读
- html - 如何使用 css 动画一张一张地加载图像?
- c++ - 有没有办法在 2 个应用程序之间传递窗口句柄 HWND?
- c++ - 为什么 const 指针意外转换为 bool?
- javascript - 动态构建表时事件在 JQuery 中不起作用
- javascript - 动态和直接加载时在 div 和 document 上的 Delegate 出现问题
- drools - Instancof 在流口水规则引擎 drl 文件中不起作用
- c - 使用 LoadLibrary() 加载的 dll 未被访问,显示错误“找不到 dll”
- java - Java:修改作为可调用对象传递的匿名函数的参数
- android - 如何从android firebase实时数据库中的onDataChange返回arrayList
- c# - 有没有办法向剃须刀 PageModel 添加扩展方法?