如何将数据保存在json文件中? [英] How to save data in json file?

查看:552
本文介绍了如何将数据保存在json文件中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 JSON.stringify

这是我当前的代码:

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));

推荐答案

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

Okay after 6 days ago I discover best solution, how to connect between Angular 6 and Node.js + json File directly and dynamically .

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文件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆