Convert Javascript Object (incl. functions) to String

后端 未结 10 995
你的背包
你的背包 2020-12-29 21:35

Hey, Im trying to convert specific javascript objects to a String. So far I\'m working with json2.js. As soon as my Object contain functions, those functions are stripped. I

10条回答
  •  囚心锁ツ
    2020-12-29 22:08

    // utility for logging
    var log = function(s){
      var d = document.getElementById('log');
      var l = document.createElement('div');
      l.innerHTML = (typeof s === 'object')?JSON.stringify(s):s;
      d.appendChild(l);
    }
    
    
    // wrapper function
    
    var obj = {
      'x-keys': {
        'z': function(e){console.log(e);},
        'a': [function(e){console.log('array',e);},1,2]
      },
      's': 'hey there',
      'n': 100
    };
    log(obj);
    
    // convert the object to a string 
    function otos(obj){
      var rs = '';
      var not_first = false;
      
      for(var k in obj){
        if(not_first) rs += ',';
        if(typeof obj[k] === 'object'){
          rs +=  '"'+k+'": {'+otos(obj[k])+'}';
        }
        else if(typeof obj[k] === 'string' || typeof obj[k] === 'function'){
          rs += '"'+k+'":"'+obj[k]+'"';
        }
        else if(typeof obj[k] === 'number'){
          rs += '"'+k+'":'+obj[k]+'';
        }
        else {
          // if it gets here then we need to add another else if to handle it
          console.log(typeof obj[k]);
        }
        not_first = true;
      }
      return rs;
    }
    // convert a string to object
    function stoo(str){
      // we doing this recursively so after the first one it will be an object
      try{
        var p_str = JSON.parse('{'+str+'}');
      }catch(e){ var p_str = str;}
      
      var obj = {};
      for(var i in p_str){
        if(typeof p_str[i] === 'string'){
          if(p_str[i].substring(0,8) === 'function'){
            eval('obj[i] = ' + p_str[i] );
          }
          else {
            obj[i] = p_str[i];
          }
        }
        else if(typeof p_str[i] === 'object'){
          obj[i] = stoo(p_str[i]);
        }
      }
      return obj;
    }
    
    // convert object to string
    var s = otos(obj);
    log(s);
    // convert string to object
    var original_obj = stoo(s);
    
    log(original_obj);
    log( original_obj['x-keys'].z('hey') );
    log( original_obj['x-keys'].a[0]('hey') );

    I realize this is very old but I have a solution here

    https://jsfiddle.net/stevenkaspar/qoghsxhd/2/

    May not work for all cases but it is a good start

    It will convert this into a string and then back into an object and you can run the functions

    var obj = {
      'x-keys': {
        'z': function(e){console.log(e);},
        'a': [function(e){console.log('array',e);},1,2]
      },
      's': 'hey there',
      'n': 100
    };
    

提交回复
热议问题