Convert Javascript Object (incl. functions) to String

后端 未结 10 996
你的背包
你的背包 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 21:52

    Actually, I think it is possible and easy. At least when doing jsonP with nodeJS it works for me just fine, and it's demonstratable by the following fiddle. I did it by simply adding strings to a function:

    var anyString = '';
    var aFunction = function() { return true; };
    var functionToText = anyString + aFunction;
    console.log(functionToText);
    

    here's the fiddle: http://jsfiddle.net/itsatony/VUZck/

    0 讨论(0)
  • 2020-12-29 21:58

    functionName.toString() will return a string of all the function code. I cut is after the name.

    var funcString = CurrentButton.clickFunc.toString();
    console.log("calling:" + funcString.substr(0, funcString.indexOf(")")-1));
    
    0 讨论(0)
  • 2020-12-29 21:59

    I made a improved version based on the @SIMDD function, to convert all types of objects to string.

    Typescript code:

    function anyToString(valueToConvert: unknown): string {
        if (valueToConvert === undefined || valueToConvert === null) {
            return valueToConvert === undefined ? "undefined" : "null";
        }
        if (typeof valueToConvert === "string") {
            return `'${valueToConvert}'`;
        }
        if (
            typeof valueToConvert === "number" ||
            typeof valueToConvert === "boolean" ||
            typeof valueToConvert === "function"
        ) {
            return valueToConvert.toString();
        }
        if (valueToConvert instanceof Array) {
            const stringfiedArray = valueToConvert
                .map(property => anyToString(property))
                .join(",");
            return `[${stringfiedArray}]`;
        }
        if (typeof valueToConvert === "object") {
            const stringfiedObject = Object.entries(valueToConvert)
                .map((entry: [string, unknown]) => {
                    return `${entry[0]}: ${anyToString(entry[1])}`;
                })
                .join(",");
            return `{${stringfiedObject}}`;
        }
        return JSON.stringify(valueToConvert);
    }
    

    Vanilla Javascript code:

    function anyToString(valueToConvert) {
        if (valueToConvert === undefined || valueToConvert === null) {
            return valueToConvert === undefined ? "undefined" : "null";
        }
        if (typeof valueToConvert === "string") {
            return `'${valueToConvert}'`;
        }
        if (typeof valueToConvert === "number" ||
            typeof valueToConvert === "boolean" ||
            typeof valueToConvert === "function") {
            return valueToConvert.toString();
        }
        if (valueToConvert instanceof Array) {
            const stringfiedArray = valueToConvert
                .map(property => anyToString(property))
                .join(",");
            return `[${stringfiedArray}]`;
        }
        if (typeof valueToConvert === "object") {
            const stringfiedObject = Object.entries(valueToConvert)
                .map((entry) => {
                return `${entry[0]}: ${anyToString(entry[1])}`;
            })
                .join(",");
            return `{${stringfiedObject}}`;
        }
        return JSON.stringify(valueToConvert);
    }
    

    ATENTION!

    I am using the function Object.entries(), winch currently is a draft. So if you are not using Babel or typescript to transpile your code, you can replace it with a for loop or the Object.keys() method.

    0 讨论(0)
  • 2020-12-29 22:01

    Use String() function http://www.w3schools.com/jsref/jsref_string.asp

    var f = function(a, b){
        return a + b; 
    }
    var str = String(f);
    
    0 讨论(0)
  • 2020-12-29 22:02

    Just provide the object to this function. (Look for nested function) Here:

    function reviveJS(obj) {
      return JSON.parse(JSON.stringify(obj, function (k, v) {
        if (typeof v === 'function') {
          return '__fn__' + v;
        }
        return v;
      }), function (k, v) {
        if (typeof v === 'string' && v.indexOf('__fn__') !== -1) {
          return v;
        }
        return v;
      });
    }

    UPDATE

    A slightly decent code than above which I was able to solve is here http://jsfiddle.net/shobhit_sharma/edxwf0at/

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题