Convert Javascript Object (incl. functions) to String

后端 未结 10 1066
你的背包
你的背包 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:05

    convert obj to str with below function:

    function convert(obj) {
      let ret = "{";
    
      for (let k in obj) {
        let v = obj[k];
    
        if (typeof v === "function") {
          v = v.toString();
        } else if (v instanceof Array) {
          v = JSON.stringify(v);
        } else if (typeof v === "object") {
          v = convert(v);
        } else {
          v = `"${v}"`;
        }
    
        ret += `\n  ${k}: ${v},`;
      }
    
      ret += "\n}";
    
      return ret;
    }
    

    input

    const input = {
      data: {
        a: "@a",
        b: ["a", 2]
      },
    
      rules: {
        fn1: function() {
          console.log(1);
        }
      }
    }
    
    const output = convert(obj)
    

    output

    `{
      data: {
        a: "@a",
        b: ["a", 2]
      },
      rules: {
        fn1: function() {
          console.log(1);
        }
      }
    }`
    
    // typeof is String
    

提交回复
热议问题