SAPUI5 change json file - json

I have create a json file config.json and a json exteded class to manager this json file.
Basically I'd like to read and update this file.
To read:
init : function(fnSuccess, scope) {
this.setDefaultBindingMode(sap.ui.model.BindingMode.TwoWay);
this.loadData("conf.json");
this.attachRequestCompleted(function() {
window.url = this.getProperty("/config/url");
window.port = this.getProperty("/config/port");
window.ldap = this.getProperty("/config/ldap");
if(typeof fnSuccess === 'function')
fnSuccess(scope);
});
},
It worked fine!
Now, to update the file:
save: function(url, port, ldap){
if(url != null)
this.setProperty("/config/url", url);
if(port != null)
this.setProperty("/config/port", port);
if(ldap != null)
this.setProperty("/config/ldap", ldap);
console.log(this.getJSON());
}
The console.log(this.getJSON()) print my changed JSON model, but when I reload or open the conf.json file, nothing was changed!
Is it possible to do that?
Thanks.

Related

Javascript Display an Error for malformed JSON object in a loop

i am writing a script that loads an array of JSON objects from a file and check if the individual element or Json object is malformed, then it throws an error.
i want to run a loop on the array to list out the faulty json objects.
please how do i go about it.
heres my code.
//function to load the json file from the host - works perfectly..
function loadJsonFile(file, callback) {
var rawFile = new XMLHttpRequest();
rawFile.overrideMimeType("application/json");
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function() {
if (rawFile.readyState === 4 && rawFile.status == "200") {
callback(rawFile.responseText);
}
}
rawFile.send(null);
}
//load the json file and parse the data.
loadJsonFile("test_data.json", function(text){
var data = JSON.parse(text);
runTestCases(data);
});
//run a test on each json object and log out the faulty ones..
//if the loop throws an error at any point it should continue to the nest node
//within the loop,and should not stop there until it has finished.
const runTestCases = (obj) => {
obj.forEach((o, v)=>{
try{
// how do test for a malformed json object
}catch(error){
throw new Error('this json object wasnt formed properly');
}
});
console.log(testShape);
}

can't read a file from tmp dir in Linux

I am writing an electron app which creates a file in user's system in tmp dir with an extension (.tms) and afterwords read that tmp dir and get all the files with an extension (.tms) and pick one file and read it's content and further parse the content using JSON.parse() . The files has contents in JSON string , so I need to parse that string obj. But my code read the dir like {/tmp/12321212.tms} but can't read the content from that dir. That's why JSON.parse function is giving error. Below is the piece of code.
function getScreenshotName (){
return new Promise( (resolve,reject) =>{
var files = readDir.readSync(os.tmpdir()+'/',["**.tms"])
if (files.length > 0 ) {
return resolve(files[0])
}
else{
return reject(err)
}
})
}
function getScreenshotObj (pathToFirstFile) {
return new Promise ((resolve,reject) =>{
console.log("Path to temp dir : " + pathToFirstFile)
fs.readFile(pathToFirstFile, 'utf8',function(err,fileContents){
if (err) {
return reject(err)
}
else{
console.log("File contents : ")
console.log(fileContents)
screenshotObject = JSON.parse(fileContents)
obj = {pathToFirstFile : pathToFirstFile , screenshotObject:screenshotObject ,accesstoken : accesstoken}
return resolve(obj)
}
})
})
}
Error is in JSON.Parse function because it can't read the contents .

FYI: In Phonegap APP for Windows Phone Console.log in change object type into String

FYI
Phonegap build for Windows Phone
I found that if we console any object it change object data type into string.
One way which I used, create your own logger and before logging create a clone of object so your object will be save.
function clone(obj) {
if (null == obj || "object" != typeof obj) return obj;
var copy = obj.constructor();
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
}
return copy;
}
function MyLogger(realMsg) {
var msg = clone(realMsg);
console.log(msg);
}

How to pass API url JSON http.get res.json(data) using express.js

I am trying to send a JSON object back to my client using a websites API and am getting the following error.
var body = JSON.stringify(obj, replacer, spaces);
TypeError: Converting circular structure to JSON
at Object,stringify (native)
Here is my code
app.get('/api/test', function(req, res){
http.get('http://api.biblia.com/v1/bible/content/LEB.txt.json?passage=John3.16&key=fd37d8f28e95d3be8cb4fbc37e15e18e', function(data) {
res.json(data);
});
});
If I replace data with a simple JSON object {"test":"test"}. Everything works fine. Any help with understanding what is even occuring would be helpful. I am using an Express.js Node.js Angular.js stack. Thank you!
The data variable in your callback is actually an instance of http.IncomingMessage, which is much more complex than just data. The error you're getting is because it has circular references, so you need to filter it out. There is an answer here that outlines this process using the code below:
var cache = [];
JSON.stringify(o, function(key, value) {
if (typeof value === 'object' && value !== null) {
if (cache.indexOf(value) !== -1) {
// Circular reference found, discard key
return;
}
// Store value in our collection
cache.push(value);
}
return value;
});
cache = null; // Enable garbage collection

Struts 2 + JSON + AJAX pdf downloading issue

I have a script in which on Click on link i need to download PDF file present in temp folder on server and this i am doing it by calling AJAX function. that AJAX function is calling struts 2 action method which is reading content of the file and write it to output stream.
and now problem is if that file is not present in temp folder. that is throwing exception. so i decided to handle it by using json. if that file exist in temp folder. i am mapping the key to
jsonObject.put("exist", true)
and if that file does not exist in temp folder. i am mapping the key to
jsonObject.put("exist", false)
and in struts.xml i am handling the action by with this way
<action name="DisplayStaticPdf"
class="com.ui.DisplayStaticPdfAction">
<result name="success" type="json"/>
</action>
and in script i am handling it through this way
function downloadDoc(actionName){
$.ajax({
url: actionName,
type: 'post',
dataType: 'json',
error: function(data) {
if(data.exist!= null && data.exist == 'false'){
alert('The document you are trying to download does not exist at location. Please make sure file exist .');
}
},
success: function() {
}
});
}
and when file is not present, it is showing me the same alert. but when file is not present, it does nothing and does not download the pdf present in temp folder.
my action class looks like ->
String pdfFileName = null;
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
String rawFileName = "abc.pdf";
String returnString = "fileNotExist";
jsonObject = new JSONObject();
ServletOutputStream out = response.getOutputStream();
response.setContentType("application/pdf");
URL url = new URL(fileURL);
URLConnection conn = url.openConnection();
if (conn.getContentLength() != 0 && conn.getContentLength() != -1)
{
bis = new BufferedInputStream(conn.getInputStream());
bos = new BufferedOutputStream(out);
try
{
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length)))
{
bos.write(buff, 0, bytesRead);
}
jsonObject.put("exist", true);
}
returnString = SUCCESS;
}
else
{
jsonObject.put("exist", false);
returnString ="fileNotExist";
}
return returnString;
hope you guys understand my issue. Anybody please put light on this whether i am doing it in right approach. or is there is any other easy way to do it
Thanks,
Ankit