How to print or debug a value in json file - javascript

How to use a debugger like console.log() to write in JSON file and debug values.

Why don't you just save the console.log output to a file?
Right click > Save as in the Console.
Otherwise there's the console.save JavaScript that may help you if I'm understanding your question properly.
http://bgrins.github.io/devtools-snippets/#console-save
(function(console){
console.save = function(data, filename){
if(!data) {
console.error('Console.save: No data')
return;
}
if(!filename) filename = 'console.json'
if(typeof data === "object"){
data = JSON.stringify(data, undefined, 4)
}
var blob = new Blob([data], {type: 'text/json'}),
e = document.createEvent('MouseEvents'),
a = document.createElement('a')
a.download = filename
a.href = window.URL.createObjectURL(blob)
a.dataset.downloadurl = ['text/json', a.download, a.href].join(':')
e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
a.dispatchEvent(e)
}
})(console)
Usage:
console.save(data, [filename])

Related

Programmatically download the QR image

I tried to create a QR code with QRcode.js library. As of the UI, I can manually click on the button download to download it but I would to download automatically without clicking the button.
Base on my code bellow.
function genQR(link_string){
let qr_code_element = document.querySelector(".qr-code");
if (link_string != "") {
if (qr_code_element.childElementCount == 0) {
generate(qr_code_element, link_string);
} else {
qr_code_element.innerHTML = "";
generate(qr_code_element, link_string);
}
} else {
alert("not valid QR input");
qr_code_element.style = "display: none";
}
}
function generate(qr_code_element, link_string) {
qr_code_element.style = "";
var qrcode = new QRCode(qr_code_element, {
text: link_string,
width: 200,
height: 200,
colorDark : "#000000",
colorLight : "#ffffff",
correctLevel: QRCode.CorrectLevel.H
});
let download = document.createElement("button");
// qr_code_element.appendChild(download);
let download_link = document.createElement("a");
download_link.setAttribute("download", "qr.png");
download_link.setAttribute("id", "downloadbtn");
download_link.innerText = "Download";
// download.appendChild(download_link);
let qr_code_img = document.querySelector(".qr-code img");
let qr_code_canvas = document.querySelector("canvas");
if (qr_code_img.getAttribute("src") == null) {
setTimeout(() => {
download_link.setAttribute("href", `${qr_code_canvas.toDataURL()}`);
}, 300);
} else {
setTimeout(() => {
download_link.setAttribute("href", `${qr_code_img.getAttribute("src")}`);
}, 300);
}
var clickEvent = new MouseEvent("click", {
"view": window,
"bubbles": true,
"cancelable": false
});
//I expect the below line will automatically download the QR but nothing fires.
download_link.dispatchEvent(clickEvent);
}
If I use button to click and download by hand will works fine for me but I want to reduce too many steps.
I think I almost done here but failed.
Could anyone show me how to automatic download?
Thank you in advance.
I've had this issue in the past, and I've worked around it by creating a small util function I can invoke upon button pressing. But invoking it directly at the end of your function should have the same result as a user click, effectively automatically downloading the QR code without user input.
export function download(blob, filename) {
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.style.display = 'none';
a.href = url;
a.download = filename
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}
I'm guessing you could try passing generate as the first parameter if the object you're getting is a Blob. Otherwise, you'll probably need to convert it before.
I done my target by adding the source you shared at the bottom of my code and then added this function to convert dataURL to Blob
function dataURItoBlob(dataURI) {
var byteString = atob(dataURI.split(',')[1]);
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
var blob = new Blob([ab], {type: mimeString});
return blob;
}
Thank you very much #Gianmarco Rengucci
I rate for you

createObjectURL() does not generate an appropriate image URL

I am using JavaScript to generate an image URL. When I opened the url generated, the image is just a small rectangle with black background, which is not the image I want at all. Hence, I am not sure where the problem is.
My response from the backend is:
filename=imageName, imageData = base64Image, dataUrl =
"data:image/gif;base64," + base64Image
str.split(':').pop().split(';')[0]; -> this line is equal to image/gif
axios.post('/convert/image', fd, {'Content-Type' : 'multipart/form-data'})
.then (res => {
// decoded = base64.decodebytes(res.data.imageData);
// console.log(decoded);
var encodedString = btoa(res.data.imageData);
// console.log(encodedString);
var decodedData = window.atob(encodedString);
var byteNumbers = new Array(decodedData.length);
for (var i = 0; i < decodedData.length; i++) {
byteNumbers[i] = decodedData.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
var str = res.data.dataUrl;
var type = str.split(':').pop().split(';')[0];
var blob = new Blob([JSON.stringify(byteArray)], {type: type});
console.log(blob);
var e = document.createEvent('MouseEvents'),
a = document.createElement('a');
a.download = 'download';
var urlCreator = window.URL || window.webkitURL;
a.href = urlCreator.createObjectURL(blob);
a.dataset.downloadurl = [type, a.download, a.href].join(':');
console.log(a.dataset.downloadurl);
e.initEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
a.dispatchEvent(e);
urlCreator.revokeObjectURL(a.href);
});

Auto download file if 'Content-Disposition' found in response using jQuery/javascript ajax

I have a rest web service for file download,
The service goto validationfilter and validate the user before generating the response.
this is my rest service responsebuilder
#GET
#Path("/logfile/{fileName}")
#Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response downloadFile(#PathParam("fileName") String fileName)
{
//get file content
ResponseBuilder response = Response.ok((Object) zipFile);
response.header("Content-Disposition", "attachment; filename=\"" + zipFile.getName() + "\"");
return response.build();
}
I am consuming the webservice using jQuery ajax. this reference is used
By above refence I am able to download my file but when I am trying to open file it gives invalid file error.
then I modified the code to
$.ajax({
type: "GET",
url: "file downloading url",
contentType: "application/octet-stream",
beforeSend: function(xhr, settings){
xhr.setRequestHeader('auth', 'authparam')
},
success: function(response, status, xhr){
var filename = "";
var disposition = xhr.getResponseHeader('Content-Disposition');
if (disposition && disposition.indexOf('attachment') !== -1)
{
var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
var matches = filenameRegex.exec(disposition);
if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
}
var type = xhr.getResponseHeader('Content-Type');
var blob = new Blob([response], { type: type + '|| mime' });
if (typeof window.navigator.msSaveBlob !== 'undefined') {
window.navigator.msSaveBlob(blob, filename);
} else {
var URL = window.URL || window.webkitURL;
var downloadUrl = URL.createObjectURL(blob);
if (filename) {
var a = document.createElement("a");
if (typeof a.download === 'undefined') {
window.location = downloadUrl;
} else {
a.href = downloadUrl;
a.download = filename;
document.body.appendChild(a);
a.click();
}
} else {
window.location = downloadUrl;
}
setTimeout(function () { URL.revokeObjectURL(downloadUrl); }, 100); // cleanup
this aso gives invalid file error
But when I access webservice using swagger ui, valid file is downloaded.

How to make json more legible

I have looked at some issues like:
How can I pretty-print JSON using JavaScript?
and
Javascript: How to generate formatted easy-to-read JSON straight from an object?
and
http://jsfiddle.net/AndyE/HZPVL/
But I cannot get it to work for me. I must be doing something wrong? Can anyone advise?
I tried adding '\t' to the stringify part, but it did not work for me
$(document).on("click", "#doBackupBtn", function(e) {
e.preventDefault();
console.log("Begin backup process");
$.when(
backup("allergies")
).then(function(allergies, log) {
console.log("All done");
//Convert to JSON
var data = {allergies:allergies}
var serializedData = JSON.stringify(data, '\t');
console.log(serializedData);
(function(console){
console.save = function(data, filename){
if(!data) {
console.error('Console.save: No data')
return;
}
if(!filename) filename = 'console.json'
if(typeof data === "object"){
data = JSON.stringify(data)
}
var blob = new Blob([data], {type: 'text/json'}),
e = document.createEvent('MouseEvents'),
a = document.createElement('a')
a.download = filename
a.href = window.URL.createObjectURL(blob)
a.dataset.downloadurl = ['text/json', a.download, a.href].join(':')
e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
a.dispatchEvent(e)
}
})(console)
The \t is on third argument. Try this on your browser console ( FF Ctrl+Shift+K ) :
console.log(JSON.stringify({"a": {"b": "c"}}, null, 4));
Result:
"{
"a": {
"b": "c"
}
}"
You are missing the JSON.stringify(obj, undefined, 2)

Add methods to Chrome Browser Console

I found a method which can create files from browser console in Chrome. I want to add this function to browsers defaults methods so that, next time I want to use that function, I dont need to paste that function and work with it again. I use this multiple times a day. Like 60 - 100 times.
Is there any way to add this function to chrome? I want this load each time I open the browser.
(function(console){
console.save = function(data, filename){
if(!data) {
console.error('Console.save: No data')
return;
}
if(!filename) filename = 'console.json'
if(typeof data === "object"){
data = JSON.stringify(data, undefined, 4)
}
var blob = new Blob([data], {type: 'text/json'}),
e = document.createEvent('MouseEvents'),
a = document.createElement('a')
a.download = filename
a.href = window.URL.createObjectURL(blob)
a.dataset.downloadurl = ['text/json', a.download, a.href].join(':')
e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
a.dispatchEvent(e)
}
})(console)
As Barmar told, bookmarlet helped me.
I am adding full code for reference.
javascript:void((function(d){var e=d.createElement('script');e.innerHTML="
(function(console){
console.save = function(data, filename){
if(!data) {
console.error('Console.save: No data');
return 0;
}
if(!filename)
filename = 'console.json';
if(typeof data === \"object\"){
data = JSON.stringify(data, undefined, 4);
}
var blob = new Blob([data], {type: 'text/json'}),
e = document.createEvent('MouseEvents'),
a = document.createElement('a');
a.download = filename;
a.href = window.URL.createObjectURL(blob);
a.dataset.downloadurl = ['text/json', a.download, a.href].join(':');
e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
a.dispatchEvent(e);
}
})(console)
";d.body.appendChild(e)})(document));

Categories

Resources