How to save data in json file? - json

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

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

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!");
});

Related

How to convert html response into json

I want to put received html response into existing json.
I have 2 pages. From first page i send post request with ajax.
At the second page i process post and read data with mysq then i echo the data and send them as response back to first page.
Again at first page i want to use this incoming response and fit it into the json.
you can view image below. this is how it looks when i write it ot the console but when i assign the value to data json object, nothing happens.
var data = {
'type': 'FeatureCollection',
'features': [{
'type': 'Feature',
'geometry': {
'type': 'Point',
'coordinates': [26.800394, 39.616144]
},
'properties': {
'title': 'Durum',
'description': '26.800394, 39.616144'
}
}, {
'type': 'Feature',
'geometry': {
'type': 'Point',
'coordinates': [28.879391, 39.418753]
},
'properties': {
'title': 'Durum',
'description': '28.879391, 39.418753'
}
},]
};
map.on('click', function(e) {
$.ajax({
type: "POST",
url: "load_data_3.php",
data:
"request=request",
success: function (response) {
value = response;
console.log(value);
},
});
data = value;
map.getSource('earthquakes').setData(data);
});
// This is the data received and then writtend to the console (This is what i see)
enter image description here

How can I map an object with index signature?

I'm about to write an app in angular. It receives an answer from an api. Inside this answer is an array indexed with strings (index signature). How can I map this array into a regular array?
The api looks like this
{
"Information": {
"Created": "2019-04-25",
"Version": "1.2"
},
"Files": {
"2019-04-26": {
'name': 'file1',
'size': 5,
},
"2019-04-25": {
'name': 'file2',
'size': 3,
},
...
}
}
And i want to map it an object that looks like this
export class Model {
'Information': {
'Created': string,
'Version': string,
};
'Files': [{
'date': Date,
'name': string,
'size': number,
}];
}
Here I would like to map the answer
getdata(url): void {
this.http.get<>(url).subscribe(data => {
// code
}
);
}
I haven't tested any of this, but, in summary, the for loop retrives all of the keys of the object data.File and the you can access this object through that key.
getdata(url): void {
this.http.get<>(url).subscribe((response: any) => {
const model: Model = new Model();
model.Files = [];
if (response.Information) {
const information: any = response.Information;
if (information.Created && information.Version) {
model.Information = {
'Created': information.Created,
'Version': information.Version
};
}
}
for (const date in data) {
if (data.File.hasOwnProperty(date)) {
const file: any = data.File[date];
model.Files.push({
'date': date,
'name': file.name,
'size': file.size
});
}
}
});
}
Object.keys(o.Files)
.map(function(k ) {
return {date: k, name: o.Files[k].name, size: o.Files[k].size}
});
It should probably look like this:
data: Array<Data>;
getData() {
this.http.get(`url`).subscribe((data) => {
this.data = data.map(item => {
const output = {};
output.information = item.information;
output.files = Object.keys(item.files).map(key => {
return {
date: new Date(key),
name: item.files[key].name,
size: item.files[key].size
};
});
return output;
});
});
}

Failed to construct 'PaymentRequest': Iterator getter is not callable

I'm following a tutorial about new PaymentRequest API but I get an error:
Uncaught TypeError: Failed to construct 'PaymentRequest': Iterator
getter is not callable.
at startPayment ((index):45)
function startPayment(){
if (!window.PaymentRequest) {
// PaymentRequest API is not available. Forwarding to
// legacy form based experience.
location.href = '/checkout';
return;
}
const methods = {
supportedMethods: "basic-card",
data: {
supportedNetworks: [
'visa', 'mastercard', 'amex', 'discover',
'diners', 'jcb', 'unionpay'
]
},
}
const details = {
total: {
label: 'Tyle musisz zabulić',
amount: { currency: 'PLN', value : '22.15' }
},
displayItems: [{
label: 'Narkotyki',
amount: { currency: 'PLN', value: '22.15' }
}],
}
const options = {
requestShipping: true,
requestPayerEmail: true,
requestPayerPhone: true,
requestPayerName: true,
shippingType: 'delivery'
};
const request = new PaymentRequest(methods, details, options) // this line fails
request.show().then(response => {
// [process payment]
// send to a PSP etc.
response.complete('success');
});
}
What does it mean and how can I fix it?
MacOS Chrome version: 72.0.3626.121 64bit
payment methods should be an array:
const methods = [
{
supportedMethods: "basic-card",
data: {
supportedNetworks: [
'visa', 'mastercard', 'amex', 'discover',
'diners', 'jcb', 'unionpay'
]
},
}
]

Module not found: Error: Can't resolve 'fs' in 'Component ' ? file.json Angular 6

import fs
fs = requier('fs')
fs index.d.ts I can see fs library but I can't use
Error in cmd
my problem if I write require cmd error
also, after installed fs of npm install fs.
same error after install or before install fs
I connect between Node.js with Angular 6 using file-saver
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');

kendoui json fill datagrid

This works fine, filling grid:
$("#grid").kendoGrid({
dataSource: {
data: [
{'id': 1, 'name': 2, 'author': 3},
{'id': 1, 'name': 2, 'author': 3},
{'id': 1, 'name': 2, 'author': 3},
] ,
},
but when I load list from getJSON:
$.getJSON('/api/notes/', function(data) {
dataSource = data.rows;
});
Pointing data to dataSource array nothing is displayed :(
If received data is in data.rows, you should do:
$("#grid").data("kendoGrid").dataSource.data = data.rows;
But, why do you not use transport.read in the grid.dataSource for loading data instead of using getJSON?
You should use the data method of the dataSource.
e.g.
$.getJSON('/api/notes/', function(data) {
dataSource.data(data.rows);
});