user10177736
user10177736

Reputation:

How to save data in json file?

I need to save JSON data into a .json file after converting an object to a string using JSON.stringify

This is my current code:

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

Note: I want to save this data dynamically, and I was used to jsonConverter of jsonTypescript2.

I tried using this method:-

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

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

Upvotes: 3

Views: 24549

Answers (2)

user10177736
user10177736

Reputation:

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

Upvotes: 6

NAVIN
NAVIN

Reputation: 3317

You can use fs.js NPM module to write data to file

There are a lot of details in the filesystem API. The most common way (as far as I know) is:

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

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

Upvotes: 4

Related Questions