【问题标题】:How to save data in json file?如何将数据保存在json文件中?
【发布时间】:2019-02-13 13:56:17
【问题描述】:

使用JSON.stringify将对象转换为字符串后,我需要将JSON数据保存到.json文件中

这是我当前的代码:

const jsonObject: object = {
      'countryName': 'Switzerland',
      'users': [
        {
          'id': 1,
          'name': 'Basel',
          'founded': -200,
          'beautiful': true,
          'data': 123,
          'keywords': ['Rhine', 'River']
        },
        {
          'id': 1,
          'name': 'Zurich',
          'founded': 0,
          'beautiful': false,
          'data': 'no',
          'keywords': ['Limmat', 'Lake']
        }
      ]
    };

const myData = JSON.stringify(jsonObject);

注意:我想动态保存这个数据,我习惯了jsonTypescript2的jsonConverter。

我试过用这个方法:-

let a = document.createElement('a');

// JSON.stringify(jsonObject), 'ex.json' // another
a.setAttribute('href', 'data:application/json;charset=UTF-8,' + encodeURIComponent(myData));

【问题讨论】:

  • 在 encodedURIComponent 方法中尝试 JSON.parse(myData)。
  • “myData”类型的参数不能分配给“字符串”类型的参数。
  • 但是如果我使用 stringify(jsonObject) 没有错误
  • 点击“a”元素后你想保存数据吗?
  • 是的,将数据保存在 jsonfile 中

标签: json node.js typescript angular6


【解决方案1】:

您可以使用fs.js NPM 模块将数据写入文件

filesystem API中有很多细节。最常见的方式(据我所知)是:

var fs = require('fs');
fs.writeFile("/fileName.json", myData, function(err) {
    if(err) {
        return console.log(err);
    }

    console.log("The file was saved!");
}); 

【讨论】:

  • var fs = require('fs');在角度 6 中不起作用:D .
  • 同样的错误:未找到模块中的警告:错误:无法解析“组件”中的“fs”
  • 如果您希望用户下载此 json 数据,则需要创建一个下载,如果您想将此 json 数据保存到您的服务器或运行应用程序的机器中,那么 Angular 将无法执行此操作。
  • 需要安装模块,使用 npm i fs
  • 我尝试安装 npm i fs 模块,但在 Angular 6 中不起作用
【解决方案2】:

好吧,在 6 天前我发现了最好的解决方案,如何在 Angular 6 和 Node.js + json 文件之间直接和动态地连接

npm install file-saver --save
import { saveAs } from 'file-saver';


const jsonObject: object = {
      'City': [
        {
          'id': 1,
          'name': 'Basel',
          'founded': -200,
          'beautiful': true,
          'data': 123,
          'keywords': ['Rhine', 'River']
        },
        {
          'id': 1,
          'name': 'Zurich',
          'founded': 0,
          'beautiful': false,
          'data': 'no',
          'keywords': ['Limmat', 'Lake']
        }
      ]
    };


const blob = new Blob([JSON.stringify(jsonObject)], {type : 'application/json'});
saveAs(blob, 'abc.json');

【讨论】:

  • 是否可以覆盖现有的 json 文件?
猜你喜欢
  • 2020-12-28
  • 1970-01-01
  • 1970-01-01
  • 2022-01-16
  • 2019-09-28
  • 2021-12-21
  • 2020-08-21
  • 2021-05-05
  • 1970-01-01
相关资源
最近更新 更多