Dump JavaScript object including function bodies as "good enough" formatted code

There are many old questions about dropping JavaScript objects.

But of those that indicate dumping the contents of functions, I can only find those that emit these functions as quoted strings (with inner quotes escaped).

What I want is something that completely removes objects, including functions, in plain old JavaScript print-ready format . .

  • I don't need full serialization and deserialization like some of the previous questions.
  • I do have to see the object as text . Just use console.log()

    requires interaction to expand the members of the object, etc. Saving the console buffer as text after console.log()

    does not result in plain js syntax, which can be quite typed.
  • Highlight placeholders or links for links that cannot be reset (circular links, DOM links, etc.). If you don't click on it, just don't linger.

Here's a naive approach that dumps the functional text, but as quoted lines that a cute printer won't format as code:

JSON.stringify(someObject, function(key, val) {
  return (typeof val === 'function') ? val.toString() : val;
}, 4);

      

For a test object, the {a: 1, b: 'bb', c: "bb", f: function e() {return "x";} }

output of the naive approach is:

{
    "a": 1,
    "b": "bb",
    "c": "bb",
    "f": "function e() {return \"x\";}"
}

      

What I need:

{
    "a": 1,
    "b": "bb",
    "c": "bb",
    "f": function e() {
        return "x";
    }
}

      

I'm glad this will be closed as a duplicate if one of the previous answers does what I want. I have looked at many of them and cannot find it.

(Use case: create a TaperMonkey login for a third party site. I need to look at what actually can be found to find places to add custom hooks. I will decorate the output, print it out, load it into a code editor, etc.)

+3


source to share


2 answers


Don't use JSON.stringifiy

- JSON cannot represent functions and therefore you will never get it to return what you want.



Since you are only targeting a specific browser, perhaps you can use uneval

or .toSource

. If you're not using Firefox, check out this polyfill .

+3


source


You can accomplish this with a simple string replacement.



var obj = {
    name: 'Bond',
    getName: function() {
        return 'James ' + this.name;
    },
    getDrink: function() {
        return "Martini";
    }
};
var result = JSON.stringify(obj, function(key, val) {
    return (typeof val === 'function') ? val.toString() : val;
}, 4);
result = result
    .replace(/"function/g, 'function')
    .replace(/}"/g, '}')
    .replace(/\\n/g, '\n')
    .replace(/\\"/g, '"');
document.querySelector('pre').innerText = result;

// Or if you actually want it as an object
eval('var obj = ' + result);
console.log(obj);
      

<pre></pre>
      

Run codeHide result


+1


source







All Articles