Populating javascript variable with JSON - javascript

I'm using phone gap, and I want to read a file out with the phone gap file api. I can read the file. But when I put my JSON into a variable it only returns '[]'.
var json;
function readFS(fileSystem) {
fileSystem.root.getFile("readme.txt", {create: true}, readFileEntry, fail);
}
function readFileEntry(fileEntry) {
fileEntry.file(gotFileread, fail);
}
function gotFileread(file){
readAsText(file);
}
function readAsText(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
console.log("Read as text");
console.log(evt.target.result);
json = evt.target.result; // this returns only []
navigator.notification.alert(evt.target.result); // this returns the real JSON :o
};
reader.readAsText(file);
}
This is the json that's in readme.txt
{"games":[{"id":"2","name":"bartje","photo":"photo2.png","description":"kimpe","length":"is","totalDownloads":"0","totalFinished":"0","locations":[{"id":"3","name":"loc21","photo":"loc21.jpg","description":"loc21","FK_Game_id":"2","lat":"51.0000","long":"4.0000","status":"0"},{"id":"5","name":"loc22","photo":"loc22.jog","description":"locatie 22","FK_Game_id":"2","lat":"51.2330","long":"40.2222","status":"1"}]},{"id":"3","name":"aa","photo":"photo3.jPg","description":"aa","length":"aa","totalDownloads":"0","totalFinished":"3","locations":[{"id":"4","name":"loc4","photo":"loc4.jpg","description":"loc4","FK_Game_id":"3","lat":"51.2191","long":"4.4021","status":"0"}]}]}
I now can retrieve the data from the file and put it in a variable. Now my only problem is I can't use it as json like
json.games[0].id
I tried doing
json = eval(evt.target.result);
But that doesn't work :o

Try:
myJson = JSON.parse(evt.target.result);
as that will create an object from the text you've read in.

This works, so it may have something to do with how you're reading the file. What do you see in console.log(evt.target.result);?
var g = {"games":[{"id":"2","name":"bartje","photo":"photo2.png","description":"kimpe","length":"is","totalDownloads":"0","totalFinished":"0","locations":[{"id":"3","name":"loc21","photo":"loc21.jpg","description":"loc21","FK_Game_id":"2","lat":"51.0000","long":"4.0000","status":"0"},{"id":"5","name":"loc22","photo":"loc22.jog","description":"locatie 22","FK_Game_id":"2","lat":"51.2330","long":"40.2222","status":"1"}]},{"id":"3","name":"aa","photo":"photo3.jPg","description":"aa","length":"aa","totalDownloads":"0","totalFinished":"3","locations":[{"id":"4","name":"loc4","photo":"loc4.jpg","description":"loc4","FK_Game_id":"3","lat":"51.2191","long":"4.4021","status":"0"}]}]}
alert(g.games[0].id) --> "2"
alert(g.games[0].locations[0].name) --> "loc21"

if evt.target.result the string
'{"games":[{"id":"2","name":"bartje","photo":"photo2.png","description":"kimpe","length":"is","totalDownloads":"0","totalFinished":"0","locations":[{"id":"3","name":"loc21","photo":"loc21.jpg","description":"loc21","FK_Game_id":"2","lat":"51.0000","long":"4.0000","status":"0"},{"id":"5","name":"loc22","photo":"loc22.jog","description":"locatie 22","FK_Game_id":"2","lat":"51.2330","long":"40.2222","status":"1"}]},{"id":"3","name":"aa","photo":"photo3.jPg","description":"aa","length":"aa","totalDownloads":"0","totalFinished":"3","locations":[{"id":"4","name":"loc4","photo":"loc4.jpg","description":"loc4","FK_Game_id":"3","lat":"51.2191","long":"4.4021","status":"0"}]}]}';
convert it to object using
var result = eval(evt.target.result);
then you can give
var games = dataObject.games;
for(var i = 0; i< games.length; i++){
var game = games[i];
// then access properties games.id, games.name, games.photo ... etc..
}

Related

Save 1st page of a PDF file using JavaScript

I need to extract 1st page of an uploaded PDF file(in SharePoint Online) & save it as a separate PDF file using JavaScript.
After some searching I found this. But I'm not able to understand how it works.
Please help.
As requested in the comment in a previous answer I am posting sample code to just get the first page in its original format, so not as a bitmap.
This uses a third party REST service that can PDF Convert, Merge, Split, Watermark, Secure and OCR files. As it is REST based, it supports loads of languages, JavaScript being one of them.
What follows is a self-contained HTML page that does not require any additional server side logic on your part. It allows a PDF file to be uploaded, splits up the PDF into individual pages and discards them all except for the first one. There are other ways to achieve the same using this service, but this is the easiest one that came to mind.
You need to create an account to get the API key, which you then need to insert in the code.
Quite a bit of the code below deals with the UI and pushing the generated PDF to the browser. Naturally you can shorten it significantly by taking all that code out.
<!DOCTYPE html>
<html>
<head>
<title>Muhimbi API - Split action</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
// ** Specify the API key associated with your subscription.
var api_key = '';
// ** For IE compatibility*
// ** IE does not support 'readAsBinaryString' function for the FileReader object. Create a substitute function using 'readAsArrayBuffer' function.
if (FileReader.prototype.readAsBinaryString === undefined) {
FileReader.prototype.readAsBinaryString = function (file_content) {
var binary_string = "";
var thiswindow = this;
var reader = new FileReader();
reader.onload = function (e) {
var bytes = new Uint8Array(reader.result);
var length = bytes.byteLength;
for (var i = 0; i < length; i++) {
binary_string += String.fromCharCode(bytes[i]);
}
thiswindow.content = binary_string;
$(thiswindow).trigger('onload');
}
reader.readAsArrayBuffer(file_content);
}
}
// ** For IE compatibility*
// ** Create a Blob object from the base64 encoded string.
function CreateBlob(base64string)
{
var file_bytes = atob(base64string);
var byte_numbers = new Array(file_bytes.length);
for (var i = 0; i < file_bytes.length; i++) {
byte_numbers[i] = file_bytes.charCodeAt(i);
}
var byte_array = new Uint8Array(byte_numbers);
var file_blob = new Blob([byte_array], {type: "application/pdf"});
return file_blob;
}
// ** Execute code when DOM is loaded in the browser.
$(document).ready(function ()
{
//** Make sure an api key has been entered.
if(api_key=='')
{
alert('Please update the sample code and enter the API Key that came with your subscription.');
}
// ** Attach a click event to the Convert button.
$('#btnConvert').click(function ()
{
// ** Proceed only when API Key is provided.
if(api_key=='')
return;
try
{
// ** Get the file object from the File control.
var source_file = document.getElementById('file_to_split').files[0];
//** Was a file uploaded?
if (source_file)
{
// ** Get the file name from the uploaded file.
var source_file_name = source_file.name;
var reader = new FileReader();
//** Read the file into base64 encoded string using FileReader object.
reader.onload = function(reader_event)
{
var binary_string;
if (!reader_event) {
// ** For IE.
binary_string = reader.content;
}
else {
// ** For other browsers.
binary_string = reader_event.target.result;
}
// ** Convert binary to base64 encoded string.
var source_file_content = btoa(binary_string);
if(source_file_content)
{
// ** We need to fill out the data for the conversion operation
var input_data = "{";
input_data += '"use_async_pattern": false';
input_data += ', "fail_on_error": false';
input_data += ', "split_parameter": 1';
input_data += ', "file_split_type": "ByNumberOfPages"';
input_data += ', "source_file_name": "' + source_file_name + '"'; // ** Always pass the name of the input file with the correct file extension.
input_data += ', "source_file_content": "' + source_file_content + '"'; // ** Pass the content of the uploaded file, making sure it is base64 encoded.
input_data += '}',
// ** Allow cross domain request
jQuery.support.cors = true;
// ** Make API Call.
$.ajax(
{
type: 'POST',
// ** Set the request header with API key and content type
beforeSend: function(request)
{
request.setRequestHeader("Content-Type", 'application/json');
request.setRequestHeader("api_key", api_key);
},
url: 'https://api.muhimbi.com/api/v1/operations/split_pdf',
data: input_data,
dataType: 'json',
// ** Carry out the conversion
success: function (data)
{
var result_code = "";
var result_details = "";
var processed_file_contents = "";
var base_file_name = "";
// ** Read response values.
$.each(data, function (key, value)
{
if (key == 'result_code')
{
result_code = value;
}
else if (key == 'result_details')
{
result_details = value;
}
else if (key == 'processed_file_contents')
{
processed_file_contents = value;
}
else if (key == 'base_file_name')
{
base_file_name = value;
}
});
// ** Show result code and details.
$("#spnResultCode").text(result_code);
$("#spnResultDetails").text(result_details);
if(result_code=="Success")
{
// ** Get first item in the array. This is the first page in the PDF
var processed_file_content = processed_file_contents[0];
// ** Convert to Blob.
var file_blob = CreateBlob(processed_file_content)
// ** Prompt user to save or open the converted file
if (window.navigator.msSaveBlob) {
// ** For IE.
window.navigator.msSaveOrOpenBlob(file_blob, base_file_name + "." + output_format);
}
else {
// ** For other browsers.
// ** Create temporary hyperlink to download content.
var download_link = window.document.createElement("a");
download_link.href = window.URL.createObjectURL(file_blob, { type: "application/octet-stream" });
download_link.download = base_file_name + ".pdf";
document.body.appendChild(download_link);
download_link.click();
document.body.removeChild(download_link);
}
}
},
error: function (msg, url, line)
{
console.log('error msg = ' + msg + ', url = ' + url + ', line = ' + line);
// ** Show the error
$("#spnResultCode").text("API call error.");
$("#spnResultDetails").text('error msg = ' + msg + ', url = ' + url + ', line = ' + line);
}
});
}
else
{
// ** Show the error
$("#spnResultCode").text("File read error.");
$("#spnResultDetails").text('Could not read file.');
}
};
reader.readAsBinaryString(source_file);
}
else
{
alert('Select file to convert.');
}
}
catch(err)
{
console.log(err.message);
// ** Show exception
$("#spnResultCode").text("Exception occurred.");
$("#spnResultDetails").text(err.message);
}
});
});
</script>
</head>
<body>
<div>
<form id="convert_form">
Select file: <input type="file" id="file_to_split" />
<br /><br />
<button id="btnConvert" type="button">Split PDF</button>
<br /><br />
Result_Code: <span id="spnResultCode"></span>
<br />
Result_Details: <span id="spnResultDetails"></span>
</form>
</div>
</body>
</html>
Big fat disclaimer, I worked on this service, so consider me biased. Having said that, it works well and could potentially solve your problem.
Finally found a solution.
First converting the uploaded PDF to image using PDF.JS, done some customization in the sample code.
Then saved the 1st page image as PDF using jsPDF.
The customized download code,
$("#download-image").on('click', function() {
var imgData = __CANVAS.toDataURL();
var doc = new jsPDF();
doc.addImage(imgData, 0, 0, 210, 300);
doc.save('page1.pdf');
});

MobileFirst POST javascript array to java array

I have an array in javascript that I am trying to pass to my mobilefirst java adapter. I call my adapter like so,
myArr = [1,2,3];
var sendPost = new WLResourceRequest(
"/adapters/MyAdpater/path",
WLResourceRequest.POST
);
var formParam = {"arr":myArr};
sendTicketPost.sendFormParameters(formParams);
Then in my adapter I can have my method and get the param
public JSONObject postAdapterFx(#FormParam("arr") List<Integer> myArray) {}
Currently when I send this I just get a 400 error and it is because the adapter doesnt like the form param as that type, so what else could I set myArray to in the adapter? I can send it as a string and then convert the string to a List<Integer> in the java but that is really messy and I would like to avoid doing that.
So how can I pass this array?
Thanks for the help
you can do it in body with request.send(yourArray). Then you can read it in Java with buffer.
Example from knowledge center
var request = WLResourceRequest(url, method, timeout);
request.send(json).then(
function(response) {
// success flow
},
function(error) {
// fail flow
}
);
You will need to take an extra step before sending the form data to the adapter. sendFormParameters only accepts objects with simple values i.e., string, integer, and boolean; in your case arr is an array.
Create a utility function that will encode the form data, you can use the following:
function encodeFormData(data) {
var encoded = '';
for(var key in data) {
var value = data[key];
if(value instanceof Array) {
encoded += encodeURI(key+'='+value.join('&'+key+'='));
} else {
encoded += encodeURI(key+'='+value);
}
encoded += '&';
}
return encoded.slice(0, -1);
}
Then you will need to update your code as follows:
var myArr = [9,2,3];
var sendPost = new WLResourceRequest("/adapters/Cool/users/cool", WLResourceRequest.POST);
var formParam = {"arr" : myArr};
sendPost.sendFormParameters(encodeFormData(formParam));

Dynamically creating ODT using WebODF / Javascript

Using javascript, I need to create an .odt file and populate the contents with data in javascript variables. The only thing that I have found that might work is WebODF. An example that seems similar to it is here.
When I am trying to do something similar to PDF with pdfkit (using node) I can do something like this:
PDFDocument = require('pdfkit');
var doc = new PDFDocument();
doc.pipe(fs.createWriteStream(fileName));
doc.text("Fist line");
doc.text("Second line");
Is it possible to do something similar to it using WebODF? I've found ops.OpInsertText, but I'm not sure how I can use it to actually insert text.
Again, ideally the solution is only in javascript.
If I got your question right, you want to create a new file dynamically using data in JavaScript variable.
You ca refer this answer to load a file from javascript variable in form of byte Array.
And this will get you up and running with a odt file ,which you can save to desired location.
function saveByteArrayLocally(error, data) {
var mime = "application/vnd.oasis.opendocument.text";
var blob = new Blob([data.buffer], {type: mime});
var res = $http({
method: 'POST', url: myWebServiceUrl,
headers: {'Content-Type': undefined},
data: blob
});
res.success(function(data, status, headers, config) {
console.log(status);
});
}
NOTE: You can use multer,express.js framework to design services as backend to save files.
This may help you.In this example I am attaching the Value returned from promt to the cursor position inside the webodf. You can similarly insert data to any other elements offest().
pressing crtl+space will show a promt, and whatever we type there is inserted to odf.
function insertBreakAtPoint(e) {
var range;
var textNode;
var offset;
var key = prompt("Enter the JSON Key", "name");
{% raw %}
var key_final = '{{address.'+key+'}}';
{% endraw %}
var caretOverlay=$('.webodf-caretOverlay').offset();
if (document.caretPositionFromPoint) {
range = document.caretPositionFromPoint(
caretOverlay.left, caretOverlay.top
);
textNode = range.offsetNode;
offset = range.offset;
} else if (document.caretRangeFromPoint) {
range = document.caretRangeFromPoint(
caretOverlay.left, caretOverlay.top
);
textNode = range.startContainer;
offset = range.startOffset;
}
#only split TEXT_NODEs
if (textNode.nodeType == 3) {
var replacement = textNode.splitText(offset);
var keynode = document.createTextNode(key_final);
textNode.parentNode.insertBefore(keynode, replacement);
}
}
function KeyPress(e) {
var evtobj = window.event? event : e
if (evtobj.keyCode == 32 && evtobj.ctrlKey)
insertBreakAtPoint();
}
document.onkeydown = KeyPress;

How do I retrieve objects from JSON received from a php file?

I have a places.php file on my server that returns the following json:
{"places":[{"poi_id":"1","poi_latitude":"53.9606","poi_longitude":"27.6103","poi_title":"Shop1","poi_category":"Shopping","poi_subcategory":"Grocery Store","poi_address":"Street 1, 1","poi_phone":null,"poi_website":null},{"poi_id":"2","poi_latitude":"53.9644","poi_longitude":"27.6228","poi_title":"Shop2","poi_category":"Shopping","poi_subcategory":"Grocery Store","poi_address":"Street 2","poi_phone":null,"poi_website":null}]}
In my javascript I use the following piece of code:
$(document).ready(function() {
var url="places.php";
$.getJSON(url,function(data){
$.each(data.places, function(i,place){
var new1 = place.poi_id;
alert(new1);
});
});
});
However the message box with the poi_id doesn't pop up. What am I doing wrong?
How about like this.
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
// data source
var jsonStr = '{"places":[{"poi_id":"1","poi_latitude":"53.9606","poi_longitude":"27.6103","poi_title":"Shop1","poi_category":"Shopping","poi_subcategory":"Grocery Store","poi_address":"Street 1, 1","poi_phone":null,"poi_website":null},{"poi_id":"2","poi_latitude":"53.9644","poi_longitude":"27.6228","poi_title":"Shop2","poi_category":"Shopping","poi_subcategory":"Grocery Store","poi_address":"Street 2","poi_phone":null,"poi_website":null}]}';
// parse json string to object
var jsonObj = JSON.parse(jsonStr);
// usage 1
console.log('iterate - without jQuery');
for (var i = 0; i < jsonObj.places.length; i++)
{
var place = jsonObj.places[i];
console.log(place.poi_id);
}
// usage 2
console.log('iterate - with jQuery');
$(jsonObj.places).each(function(index, place)
{
console.log(place.poi_id);
});
</script>
Output:
How to use this in your code:
$(document).ready(function()
{
$.getJSON("/path/to/places.php", function(data)
{
// data here will be already decoded into json object,
// so... you do this
$(data.places).each(function(index, place)
{
console.log(place.poi_id);
});
});
});
Take a look at the manual also: http://api.jquery.com/jquery.getjson/
Should work, if not leave a comment with an error or reason.
Does this do / get you closer:
for (var property in data)
{
if (data.hasOwnProperty(property))
{
console.log(property);
}
}
Is your php actually generating the JSON? If it's only getting a particular file it may be easier to choose your file using JS and AJAX it. Here's the code I use for php anyway.
function callPHP(dataToSend)
{
$.post( "places.php", dataToSend )
.done(function( phpReturn ) {
console.log( phpReturn );
var data = JSON.parse(phpReturn);
for(var i = 0;i<data.places.length;i++)
console.log(data.places[i].poi_id);
});}
}
Setting places.php file encoding to UTF-8 solved the problem

Load local .csv with js and process it with d3.js

I stuck on the following thing.
I don't have a running local http-service so I'd like to handle my file loading otherwise.
First I created the following function, as suggested in some references.
var fileArray = [];
function readSingleFile(evt) {
//Retrieve the first (and only!) File from the FileList object
var f = evt.target.files;
window.array = []
if (f) {
var r = new FileReader();
r.onload = function(e) {
var contents = e.target.result;
window.array.push(contents);
fileArray.push({name:f.name, contents: contents});
}
r.readAsText(f);
console.log(fileArray);
} else {
alert("Failed to load file");
}
}
document.getElementById('fileinput').addEventListener('change', readSingleFile, false);
Then I try to call the fileArray in a d3.csv function. But this is where I stuck - the console log just shows an empty array.
var dataset = []
d3.csv(fileArray, function(data) {
dataset = data.map(function(d) { return [ d["TEXT"], +d["HOURS"], +d["MONTH_DIGIT"] ]; });
console.log(dataset)
});
The .csv file has the following structure.
"TEXT","HOURS","MONTH_DIGIT"
"Adjustments work",849.45,"01"
How do I exactly call the file to work with d3.js?
If you want to "take the file and it's contents and work with it", you could load the file inside the d3.csv() method, after the callback and the apply the changes you wanted to make to the content.
d3.csv('/path/to/myfile.csv, function(data) {
// Modify the files data
...
// Do something with d3.js
});
For JSON:
var data = JSON.parse(JavascriptStringVariableThatContainsJSON);
For CSV:
var data = d3.csv.parseRows(JavascriptStringVariableThatContainsMyCSVdata);
//then add data to the graph and call enter, something like:
var dataEnter = svg.selectAll("rect").data(data).enter();
d3.csv tries to fetch over http/https.
You need to read the file first then use d3.csvParse on the content (in string format).
A simple example in node:
import * as d3 from "d3";
import * as fs from "fs";
const csv = fs.readFileSync("./data/data.csv", "utf8");
const data =d3.csvParse(csv);
console.log(data);

Categories