How to append JSON data to existing JSON file node.js - json

How to append an existing JSON file with comma "," as separator
anchors = [ { "title":" 2.0 Wireless " } ]
fs.appendFileSync('testOutput.json', JSON.stringify(anchors));
This current code's output is like this
[
{
"title":" 2.0 Wireless "
}
]
[
{
"title":" Marshall Major II "
}
]
How to I get this in the correct format with comma "," as separator
I want to get something like this
[
{
"title":" 2.0 Wireless "
},
{
"title":" Marshall Major II "
}
]

Try this. Don't forget to define anchors array.
var data = fs.readFileSync('testOutput.json');
var json = JSON.parse(data);
json.push(...anchors);
fs.writeFile("testOutput.json", JSON.stringify(json))

I created two small functions to handle the data to append.
the first function will: read data and convert JSON-string to JSON-array
then we add the new data to the JSON-array
we convert JSON-array to JSON-string and write it to the file
example: you want to add data { "title":" 2.0 Wireless " } to file my_data.json on the same folder root. just call append_data (file_path , data ) ,
it will append data in the JSON file, if the file existed . or it will create the file and add the data to it.
data = { "title":" 2.0 Wireless " }
file_path = './my_data.json'
append_data (file_path , data )
the full code is here :
const fs = require('fs');
data = { "title":" 2.0 Wireless " }
file_path = './my_data.json'
append_data (file_path , data )
async function append_data (filename , data ) {
if (fs.existsSync(filename)) {
read_data = await readFile(filename)
if (read_data == false) {
console.log('not able to read file')
}
else {
read_data.push(data)
dataWrittenStatus = await writeFile(filename, read_data)
if dataWrittenStatus == true {
console.log('data added successfully')
}
else{
console.log('data adding failed')
}
}
else{
dataWrittenStatus = await writeFile(filename, [data])
if dataWrittenStatus == true {
console.log('data added successfully')
}
else{
console.log('data adding failed')
}
}
}
async function readFile (filePath) {
try {
const data = await fs.promises.readFile(filePath, 'utf8')
return JSON.parse(data)
}
catch(err) {
return false;
}
}
async function writeFile (filename ,writedata) {
try {
await fs.promises.writeFile(filename, JSON.stringify(writedata,null, 4), 'utf8');
return true
}
catch(err) {
return false
}
}

Related

How to add multiple files from server response to zip file in Angular

exportIcsReportInJSONFormat() {
this.icsService.getICSReport()
.pipe(takeUntil(this.notifier))
.subscribe(response =>{
const icsReport =new Blob([response], { type: 'text/json;charset=utf-8' });
saveAs(icsReport, 'ics-report_' + new Date().toISOString() + '.json')}
);
}
exportIcsReportInCSVFormat() {
this.icsService.getICSReport()
.subscribe(
response => {
const csv = this.convertJSONToCSV(response);
const csvBlob = new Blob([csv], { type: 'text/json;charset=utf-8' });
saveAs(csvBlob, 'ics-report_' + new Date().toISOString() + '.csv');
});
}
exportIcsReportInTSEFormat() {
this.icsService.getTse()
.pipe(takeUntil(this.notifier))
.subscribe(tse => saveAs(tse, 'ics-report_' + new Date().toISOString() + '.tse'));
}
Calling the functions here to generate the files and adding them to zip:
getReports() {
const zip: JSZip = new JSZip();
this.selectedReportFormats.forEach(element => {
if (element == 'JSON') {
const JSONFile = this.exportIcsReportInJSONFormat();
zip.file("JSONFile");
}
if (element == 'CSV') {
const CSVFile = this.exportIcsReportInCSVFormat();
zip.file("CSVFile");
}
if (element == 'TSE') {
const TESFile = this.exportIcsReportInTSEFormat();
zip.file("TESFile");
}
zip.generateAsync({type:"blob"})
.then(function(content) {
// see FileSaver.js
saveAs(content, "example.zip");
});
});
}
I am doing it wrong because I can't find proper syntax to add files to zip kind of using a loop. This scenario is basically I want to download a report and I have 3 options JSON, CSV and TSE. So I have a checkbox and the options I check and click on Download I get files in all those formats added to zip and downloaded in a ZIP file.

How to make my flutter app read upadated json file instead of old json file?

I made a app where I have to first read local json file and updated some content of it inside app and save that file and without closing the app I want to display the changes by reading updated json file.
I am able to read my json file, save changes in that file but when I try to see my changes without closing the app by reading that json file, it always show my previous data. But if I close my app and open it again It show read new updated file.
How can I show changes by reading updated json file without closing the app??
This is my code:
First I read json file inside initstate:
Future<void> readJson() async {
final String response =
await rootBundle.loadString('jsonfile/primary_values.json');
final data = jsonDecode(response);
var values = PrimaryValueJson.fromJson(data);
setState(() {
if (primaryKey == 'Doctor SSN :') {
widget.primaryIndex = values.doc_ssn;
widget.primaryValue = 'DC0${widget.primaryIndex}';
print(widget.primaryValue);
print('this is readjson');
}
});
}
#override
void initState() {
super.initState();
print("I am doctor init screen");
readJson();
}
And then I increment Doc.ssn by 1 and write it by clicking a button. Function associated with that button is:
_writeJson() async {
print("this is 1st line writejson: ${widget.primaryIndex}");
String response =
await rootBundle.loadString('jsonfile/primary_values.json');
File path = File('jsonfile/primary_values.json');
var data = jsonDecode(response);
var values = PrimaryValueJson.fromJson(data);
final PrimaryValueJson doctor = PrimaryValueJson(
doc_ssn: values.doc_ssn + 1,
phar_id: values.phar_id,
ssn: values.ssn,
);
final update = doctor.toJson();
path.writeAsStringSync(json.encode(update));
print('this is writejson:${doctor.doc_ssn}');
nameController.text = '';
specialityController.text = '';
experienceController.text = '';
widget.primaryIndex = doctor.doc_ssn;
widget.primaryValue = 'DC0${doctor.doc_ssn}';
}
Future<void> insertRecord(context) async {
count = count + 1;
if (nameController.text == '' ||
specialityController.text == '' ||
experienceController.text == '') {
print("Please fill all fields");
} else {
try {
String uri = "http://localhost/hospital_MS_api/insert_doctor.php";
var res = await http.post(Uri.parse(uri), body: {
"Doc_SSN": widget.primaryValue,
"name": nameController.text,
"speciality": specialityController.text,
"experience": experienceController.text,
});
setState(() {
_writeJson();
});
var response = jsonDecode(res.body);
if (response["success"] == "true") {
print("Record Inserted");
} else {
print("Record not inserted");
}
} catch (e) {
print(e);
}
}
}
Assets are read-only. After writing an asset file to a file, read also from that file.
File path = File('jsonfile/primary_values.json');
...
path.writeAsStringSync(json.encode(update));
...
var data = jsonDecode(path.readAsBytesSync());

How to i display file from JSON object which contains an array?

Below is my json object which is returned. As you can see i have an array called "DocumentVersions" with a blob address of the file that i want to display. On the success function i want to display the image under a div. I tried looping through but i don't know how to display the image. I could have multiple files returned.
{
"FileUploadID":"27",
"DocumentVersions":[
{
"Active":true,
"DocumentVersionID":"5",
"FileName":"Logo0112.png",
"ContentLength":18846,
"ContentType":"image/png", "
"RevisionNumber":0,
"RevisionDate":"2017-08-01T12:24:04.7748026+01:00",
"Blob":"https://address/documents/75755df4af5f.png",
"BlobFileName":75755df4af5f.png"
}
],
"success":true,
"id":"27",
"message":"The Files have been uploaded"
}
Here is my success function. Where i get a 'Cannot read property 'Blob' of undefined'
myDiv.on("complete", function (data) {
res = JSON.parse(data.xhr.responseText);
console.log(res);
if (res.success == true) {
for (var key in res) {
var optionhtml = '<p="' + res[key].FileUploadID +
'">' + res[key].DocumentVersions.Blob + '</p>';
$(".test").append(optionhtml);
}
}
else {
alert(res.message);
}
});
As you can see, the DocumentVersions is not a object, it's a array with objects (only one object in this case).
{
"FileUploadID":"27",
"DocumentVersions":[
{
"Active":true,
"DocumentVersionID":"5",
"FileName":"Logo0112.png",
"ContentLength":18846,
"ContentType":"image/png", "
"RevisionNumber":0,
"RevisionDate":"2017-08-01T12:24:04.7748026+01:00",
"Blob":"https://address/documents/75755df4af5f.png",
"BlobFileName":75755df4af5f.png"
}
],
"success":true,
"id":"27",
"message":"The Files have been uploaded"
}
You need to specify the inner object in the array that you want to get data:
res[key].DocumentVersions[0].Blob
Thanks for your help, I solved my problem by using the following code this lets me get the image files and display.
res.DocumentVersions.forEach(function (obj) {
var img = new Image();
img.src = obj.Blob;
img.name = obj.FileName;
img.setAttribute("class", "fileLoad");
$("#fileupload").append(img);
});

Angular reading data from json into textarea

I'm trying to read some test data from a local json file and output the data with correct formatting into a textarea. Right now though it just outputs [object Object]. How would I go about getting it so it outputs:
Id: theIdGoesHere
Title: theTitleGoesHere
step.service.ts The service used to call the json data
public getJson(): Observable<any>{
return this.http.get('/assets/jsonData/MyJson.json')
.map(response => response.json());
}
MyJson.json
{
"data":[
{
"id": 1,
"title":"Test1"
},
{
"id": 2,
"title":"Test2"
}
]
}
main.componenet.ts
private testVar: any;
test(){
this.stepService.getJson().subscribe(data => (this.testVar = data));
}
anothermethod(){
this.test();
this.mainStepText = this.testVar; //mainStepText binded to textarea with [(ngModel)]="mainStepText"
}
get mainStepText2() { //Rebinded this one
const text = [];
const { data } = this.testVar;
for (let item of this.testVar.data) {
Object.keys(item).forEach(key => {
text.push(key + ': ' + item[key]);
});
}
return text.join('\r\n'); // \r\n is the line break
}
You can use json pipe to format your object into a json string:
[(ngModel)]="mainStepText | json"
If you want to show a specific property of your object, you can access it in your template:
[(ngModel)]="mainStepText.data[0].title"
This will display "Test1" in your field.
You could loop through your json.data and through their keys to extract the text and values and generate the string you need for the text area.
const text = [];
for (let item of this.textVar.data) {
Object.keys(item).forEach(key => {
text.push(key + ': ' + item[key]);
});
}
return text.join('\r\n'); // \r\n is the line break
Here's the running code, I put it in app.ts: http://plnkr.co/edit/3AbQYQOW0MVBqO91X9qi?p=preview
Hope this is of help.

Read csv to object of object for d3 [datamaps]

I'm using datamaps and would like to be able to read the data from a csv file.
The data format that datamaps is expecting is the following:
var loadeddata = {
"JPN":{Rate:17.5,fillKey:"firstCat"},
"DNK":{Rate:16.6,fillKey:"secondCat"}
};
I would like to read a csv file of the following structure and transform it into the format that datamaps is expecting:
ISO, Rate, fillKey
JPN, 17.5, firstCat
DNK, 16.6, secondCat
My 'best attempt' was using the following code:
var csvloadeddata;
d3.csv("simpledata.csv", function (error, csv) {
if (error) return console.log("there was an error loading the csv: " + error);
console.log("there are " + csv.length + " elements in my csv set");
var nestFunction = d3.nest().key(function(d){return d.ISO;});
csvloadeddata = nestFunction.entries(
csv.map(function(d){
d.Rate = +d.Rate;
d.fillKey = d.fillKey;
return d;
})
);
console.log("there are " + csvloadeddata.length + " elements in my data");
});
But this code generates a variable 'csvloadeddata' that looks like this:
var csvloadeddata = [
{"key": "JPN", "values": { 0: {Rate:17.5, fillKey:"firstCat"}} },
{"key": "DNK", values : { 1: {Rate:16.6,fillKey:"secondCat"}} }
];
What am I doing wrong?
Found the answer myself. If somebody is interested – this is what I ended up using:
<script>
d3.csv("simpledata.csv", function(error, csvdata1) {
globalcsvdata1 = csvdata1;
for (var i=0;i<csvdata1.length;i++)
{
globalcsvdata1[ globalcsvdata1[i].ISO] = globalcsvdata1[i] ;
//console.log(globalcsvdata1[i]);
delete globalcsvdata1[i].ISO;
delete globalcsvdata1[i] ;
}
myMap.updateChoropleth(globalcsvdata1);
}
);
var myMap = new Datamap({
element: document.getElementById('map'),
scope: 'world',
geographyConfig: {
popupOnHover: true,
highlightOnHover: false
},
fills: {
'AA': '#1f77b4',
'BB': '#9467bd',
defaultFill: 'grey'
}
});
</script>
</body>
The csv has the following structure:
ISO,fillKey
RUS,AA
USA,BB
Here is a working example: http://www.explainingprogress.com/wp-content/uploads/datamaps/uploaded_gdpPerCapita2011_PWTrgdpe/gdpPerCapita2011_PWTrgdpe.html