I’m trying to find a way to "pretty print" a JavaScript data structure in a human-readable form for debugging.
I have a rather big and complicated data structure being stored in JS and I need to write some code to manipulate it. In order to work out what I’m doing and where I’m going wrong, what I really need is to be able to see the data structure in its entirety, and update it whenever I make changes through the UI.
All of this stuff I can handle myself, apart from finding a nice way to dump a JavaScript data structure to a human-readable string. JSON would do, but it really needs to be nicely formatted and indented. I’d usually use Firebug’s excellent DOM dumping stuff for this, but I really need to be able to see the entire structure at once, which doesn’t seem to be possible in Firebug.
I wrote a function to dump a JS object in a readable form, although the output isn’t indented, but it shouldn’t be too hard to add that: I made this function from one I made for Lua (which is much more complex) which handled this indentation issue.
Here is the ‘simple’ version:
I will look at improving it a bit.
Note 1: To use it, do
od = DumpObject(something)and use od.dump. Convoluted because I wanted the len value too (number of items) for another purpose. It is trivial to make the function return only the string.Note 2: it doesn’t handle loops in references.
EDIT
I made the indented version.
Choose your indentation on the line with the recursive call, and you brace style by switching the commented line after this one.
… I see you whipped up your own version, which is good. Visitors will have a choice.