Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save a Javascript object to file ?

Tags:

javascript

I need to save a complex javascript object to a file for later investigation. It is a very big object, more then 50 methods and propeties.

I can see the object and its methods and properties (and its values) in Firefox-Firebug on DOM page, but i can't save it to a file from there.

I want save the object with current values of properties, not the HTML doc. Any format of a file - HTML or JSON or anything else is good for me :)

How can I save the object?

like image 769
János Továbbító Avatar asked Sep 26 '12 08:09

János Továbbító


3 Answers

Well... There is something you can do, but I can't say how ugly is. You can do something like

JSON.stringify(my_big_javascript_object) and then save the resulting JSON (plain text) in a file.

You can look at the values later using some JSON viewer, like http://jsonviewer.stack.hu/

like image 154
alexandernst Avatar answered Oct 24 '22 15:10

alexandernst


It is possible now using the Blob API:

  function downloadObject(obj, filename){
    var blob = new Blob([JSON.stringify(obj, null, 2)], {type: "application/json;charset=utf-8"}).slice(2,-1);
    var url = URL.createObjectURL(blob);
    var elem = document.createElement("a");
    elem.href = url;
    elem.download = filename;
    document.body.appendChild(elem);
    elem.click();
    document.body.removeChild(elem);
  }

You can read more about it here: https://developer.mozilla.org/en-US/docs/Web/API/Blob

It requires that you have a webpage up with a live DOM, which should work if you are in the middle of debugging javascript on a page.

like image 10
kashiraja Avatar answered Oct 24 '22 16:10

kashiraja


This works well for me.

//Initialization of object to save
var objectToSave={first:'string', second: function(){}};
//Start of saving method
var textToSave='';//String to be saved
var count=0;
for(var i in objectToSave){
//Adding every key name + type + text value to string
textToSave+=objectToSave[i].constructor.name+' '+ Object.keys(objectToSave)[count]+' = '+objectToSave[i]+'\n';
count++;
}
//Saving string to file using html clicking trick
var hiddenElement = document.createElement('a');
hiddenElement.href = 'data:attachment/text,' + encodeURI(textToSave);
hiddenElement.target = '_blank';
hiddenElement.download = 'myFile.txt';
hiddenElement.click();

Result of this method is saved txt file with text:

String first = string

Function second = function (){}

like image 3
PolyGlot Avatar answered Oct 24 '22 16:10

PolyGlot