Dmitry Dmitry - 7 months ago 17
JSON Question

Is it possible to encode javascript object to javascript(rather than json)?

I know it is possible to convert a JavaScript data object to JSON using JSON.stringify. e.g:

var cat = {
soundString: 'Meow!'

Then call JSON.stringify(cat) to get

I am interested to know if it is possible to have a parallel to this, except instead of turning the JavaScript object into JSON, turn it into a JavaScript string that can be evaluated back to the object.

var cat = {
meow: function() {

I want something that would take the cat object and produce a string
"{meow: function(){console.log('Meow!');}}"
, which can be parsed back using eval.

Can this be accomplished?


Write a recursive deep copy method and check for Array.isArray(item)

Use .hasOwnProperty to avoid the prototype chain

Put additional quotations wherever you want

var str = "{"
for (var key in cat) {
    str += key + ":" + cat[key] + ","
str = str.substr(0, str.length-1) + "}"