i want to edit an json file using javascript. the file is "client.json" and is at the local system and is modified at local system only. I am using form for creating the new client details and i want that those details to be appended to the json file as the object.
{"clients":[
{
"name":"xxxx",
"team":"yyy",
"location": {
"city":"beijing",
"country":"china"
},
"wdays":{"start":"Monday","end":"friday"},
"whours":{"start":"9 A.M","end":"6 P.M" }
},
{
"name":"xxxx",
"team":"yyy",
"location": {
"city":"new york",
"country":"usa"
},
"wdays":{"start":"Monday","end":"friday"},
"whours":{"start":"9 A.M","end":"6 P.M" }
}
]}
the following the javascript code is about reading data from form and appending that data as the json object.........`
</script>
<script type="text/javascript">
function addtojson()
{
var client_name=(document.getElementById("cname")).value;
var country=document.getElementById("country").value;
var city=document.getElementById("city").value;
var wtimeto=document.getElementById("wtimeto").value;
var wtimefrom=document.getElementById("wtimefrom").value;
var wdayto=document.getElementById("wdayto").value;
var wdayfrom=document.getElementById("wdayfrom").value;
jQuery.getJSON('client.json')
.done(function(data) {
var cobj=new Object();
cobj.name=client_name;
cobj.team="YYY";
cobj.location=new Object();
cobj.location.city=city;
cobj.location.country=country;
cobj.wdays=new Object();
cobj.wdays.start=wdayto;
cobj.wdays.end=wdayfrom;
cobj.whours=new Object();
cobj.whours.start=wtimeto;
cobj.whours.end=wtimefrom;
var myString = JSON.stringify(cobj);
alert('I am working');
alert(myString);
data.clients.push(cobj);
alert(JSON.stringify(data.clients[0]));//it gives previous first array object
alert(JSON.stringify(data.clients[1]));//it gives previous second array object
alert(JSON.stringify(data.clients[2]));//it gives the new appended array object
});
return true;
}
</script>`
though the data is being modified locally in the program the json file is not getting updated????????
JavaScript in a browser is generally not permitted to write to the local disk. Regardless, after you load the JSON file, you're editing the loaded document in memory, which has no impact on the file on the disk until you write the changes to disk. This is where you will run into the problem of not being allowed to write to disk from a script.
You might be able to get something going using dynamically-generated data: URI's to trigger a download prompt to download the new version of the file and save it to disk. See http://en.wikipedia.org/wiki/Data_URI_scheme for more info.
Related
I'm looking for some guidance or ideas on how to create a proper formatted Excel (XLSX) spreadsheet using Javascript Serverside.
I've found multiple sites/libraries (such as SheetJS) which can create the file, but depend on web functions (ie. blobs and the like).
Alternatively a JS library which similarly can create a zip file without using blobs/web functions (ie. i can create the XML files structured within the XLSX file/zip but cannot compress server side.
The reason for this is the need to export these files on Server Side scripts within NetSuite/SuiteScript... so far I've come up empty.
You may be able to get what you are looking for using the 'N/file' SuiteScript module. Create a file using file.Type.EXCEL
Here's a scheduled script code sample that will take saved search results and create an excel file that is saved to the file cabinet. You can reference Suite Answer Id 93557. Also the "file.Type" enum does allow for the type Zip, reference Suite Answer Id 43530
define(['N/search','N/file'], function(search, file) {
function execute(scriptContext){
//Load saved search
var mySearch = search.load({id: '47'});
//Run saved search
var mySearchResultSet = mySearch.run();
//Headers of CSV File separated by commas and ends with a new line (\r\n)
var csvFile = 'Internal ID,Item Name,Average Cost\r\n';
//Iterate through each result
mySearchResultSet.each(iterator);
function iterator(resultObject){
//get values
var internalid = resultObject.getValue(mySearch.columns[0])
var itemid = resultObject.getValue(mySearch.columns[1])
var formulacolumn = resultObject.getValue(mySearch.columns[2])
//Add each result as a new line on CSV
csvFile += internalid+','+itemid+','+formulacolumn+'\r\n'
return true;
}
//Variable for datetime
var date = new Date();
//Creation of file
var fileObj = file.create({
name: 'Saved Search Result - ' + date.toLocaleDateString() +'.xlsx',
fileType: file.Type.EXCEL,
contents: csvFile,
description: 'This is a CSV file.',
encoding: file.Encoding.UTF8,
folder: 123
});
//Save the CSV file
var fileId = fileObj.save();
}
return {
execute: execute
};
});
I am trying to write a gmail add-on where I iterate over all emails and create a report based on their producers. Iterating over emails is the easiest part and I have done that, however I can't find any way to get producer line of each PDFs.
So far I tried
analyzing the blob, however this is something like writing a PDF library to parse all syntax. producer tag is not clearly present
adding pdf.js, which is a third party open source tool to extract such information. However, I couldn't add it due to ES3 - ES6 support issue.
What's the best way to get the producer line of a PDF in google app script?
Thank you
You want to retrieve the value of Producer from PDF file.
I could understand like above. If my understanding is correct, how about this sample script? In this sample script, from your shared PDF files, the value of Producer is retrieved by 2 regular expressions from the file content. Please think of this as one of several answers.
Sample script:
When you use this script, please set the folder ID of folder that PDF files are put. This script retrieves the value from all PDF files in a folder.
var folderId = "### folderId ###";
var files = DriveApp.getFolderById(folderId).getFilesByType(MimeType.PDF);
var regex = [/Producer\((\w.+)\)/i, /<pdf:Producer>(\w.+)<\/pdf:Producer>/i];
var result = [];
while (files.hasNext()) {
var file = files.next();
var content = file.getBlob().getDataAsString();
var r = regex.reduce(function(s, e) {
var m = content.match(e);
if (Array.isArray(m)) s = m[1];
return s;
}, "");
result.push({
fileName: file.getName(),
fileId: file.getId(),
vaueOfProducer: r,
});
}
Logger.log(result); // Result
Result:
This sample result was retrieved from a folder (my Google Drive) that the shared 3 PDF files were put.
[
{
"fileName": "2348706469653861032.pdf",
"fileId": "###",
"vaueOfProducer": "iText� 7.1.5 �2000-2019 iText Group NV \(iText; licensed version\)"
},
{
"fileName": "Getting started with OneDrive.pdf",
"fileId": "###",
"vaueOfProducer": "Adobe PDF library 15.00"
},
{
"fileName": "DITO-Salesflow-040419-1359-46.pdf",
"fileId": "###",
"vaueOfProducer": "iText 2.1.7 by 1T3XT"
}
]
Note:
About the file of 2348706469653861032.pdf, the characters which cannot be displayed are included in the value of Producer.
This is a sample script. So please modify this for your situation.
I'm trying to display this code with JSONView but won't display when calling the data from inside the api callback function, but will display non api data when placed outside the callback.
// Call FreeGeoIP API to get browser IP address
$.getJSON('https://freegeoip.net/json/', function(data) {
var ipaddress = data.ip;
// Get browser language
var language = window.navigator.language;
// Get software
var software = window.navigator.appVersion;
var regExp = /\(([^)]+)\)/;
software = regExp.exec(software)[1];
// Add data to obj
var obj = {
'ipaddress': ipaddress,
'language': language,
'software': software
};
// Write obj to document
$('body').html(JSON.stringify(obj));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
JSONView extension or any other extensions in the Chrome browser needs permission to access file URLs if it is accessing files from your local system.
To allow:-
Visit chrome://extensions/
Click on Details button of the Extension card
Switch ON the Allow access to file URLs
JSONView or any other json formatter detects if you are viewing json on basis on contentType of the document loaded (as set on http header).
Since you must be running this code on client side (browser) the contentType is set to text/html .
For the plugin to correctly format the json, it must know that what you're looking at is indeed json and it does so by reading contentType header.
That is why fetching json via this script shows json as text in body attribute but not picked up by the plugin.
I have a Google Sheets file with an attached Script. The script does a number of things, one is it makes a clone of it self using makeCopy. This portion works. Now I want to be able to keep the same cloned Google file name and same Google file ID and just update the content which includes a Spreadsheet and the associated Google script.
if (!fileFound){
var file = masterSSFile.makeCopy(reportFileName, RepFolder);
} else {
oldFile.setContent(masterSSFile.getBlob());
}
When I use makeCopy with the same file name it creates a second file with the same name but with a different file ID.
The else portion fails because .setContent argument seems to just accept text. The result is the word "Blob" in the oldFile, everything else is gone.
I have other scripts that update the contents of a existing spreadsheet by overriding the contents of the various sheets, but I also want the associated script to also be included in the updated file keeping the same file ID.
I found this....
Overwrite an Image File with Google Apps Script
and tried using
var masterSpreadsheetID = SpreadsheetApp.getActiveSpreadsheet().getId();
var masterSpreadsheetFile = DriveApp.getFileById(masterSpreadsheetID);
var oldFileID = oldFile.getId();
var oldFileName = oldFile.getName();
var newBlob = masterSpreadsheetFile.getBlob();
var file = {
title: oldFileName,
mimeType: 'application/vnd.google-apps.spreadsheet'
};
var f = Drive.Files.update(file, oldFileID, newBlob);
I get error: "We're sorry, a server error occurred. Please wait a bit and try again. " on this line: "Drive.Files.update(file, oldFileID, newBlob);"
After reading this:
https://github.com/google/google-api-nodejs-client/issues/495
it looks like Drive.Files.update(), does not support bound scripts.
I'm trying to write data to a json file after hitting "Submit" on an html formly-form using only angular, but nothing is happening. I know I can read a json file using angular but not sure on creating files.
onSubmit() in controller:
function onSubmit() {
$scope.save = function() {
$http.post('./temp/sample_data.json', JSON.stringify($scope.model)).then(function(data) {
$scope.msg = 'Data saved';
});
};
};
html:
<form name="form" ng-submit="onSubmit()" novalidate>
<formly-form model="model" fields="fields"></formly-form><br/>
<button type="submit">Submit</button>
</form>
The sample_data.json isn't created and if I create an empty file it does not fill up with the data as well. The $scope.model defenitly contains data.
If anyone can help, it will be very appreciated.
Thanks, Alon.
Is it possible to write data to a locally json file with nothing but angular?
No. Even if you're running the page from the local file system (e.g., file://myfile.html) or from a local webserver (e.g., http://localhost/myfile.html or http://host-on-my-intranet/myfile.html), you still have no means of directly writing to a file from browser-hosted JavaScript code.
Two choices:
Send it to something (e.g., a server) that can write it out, or
Provide it as a data: URI (if feasible in your case) that the user can right-click and choose "save as..."
Here's how you create a data: URI for some JSON text:
var uri = "data:application/json;charset=UTF-8," + encodeURIComponent(theJSON);
Full Example of #2:
var theData = {
foo: "bar"
};
var theJSON = JSON.stringify(theData);
var uri = "data:application/json;charset=UTF-8," + encodeURIComponent(theJSON);
var a = document.createElement('a');
a.href = uri;
a.innerHTML = "Right-click and choose 'save as...'";
document.body.appendChild(a);
No.
Angular runs client side.
If you want to write data to the server (even one on the same computer as the browser) then you need server side code to do it.
You can't access the local filesystem (directly) from Javascript. This is enforced for security reasons (and makes sense when you think about it!).
Local file access with javascript
Since this is not possible you could try another route. Your $scope.save was not being invoked by the way, only assigned.
$scope.save = function() {
localStorage.model = JSON.stringify($scope.model);
};
function onSubmit() {
$scope.save();
$scope.msg = 'saved';
};
To get your model back do this on init:
if (localStorage.model)
$scope.model = JSON.parse(localStorage.model);
The following code adds a download button for a JSON object.
Note: wrapping a button with an anchor tag is not recommended for HTML 5 yet it works in Chrome which is all I needed. YMMV.
HTML:
<a download="my-json-object.json" [href]="dataUri">
<button>Download</button>
</a>
Typescript:
get dataUri(): SafeUrl {
const jsonData = JSON.stringify(this.dataSource);
const uri = 'data:application/json;charset=UTF-8,' + encodeURIComponent(jsonData);
return this.sanitizer.bypassSecurityTrustUrl(uri);
}