How to recurse through any parsed JSON Ruby object
Today I wanted to recurse through all of the values in some parsed JSON Ruby objects (I had a practical reason for this). I approached the problem in a very similar way as when I solved this other problem: counting the number of times a symbol appears in an S-expression. This post shows the method (after a little refactoring) I wrote to do this.
Is the approach here pretty pointless if a standard library thing I don’t know about does the same thing and would be more obvious? Even so, the method here is somewhat interesting and the post is a good review of JSON, recursion, and Ruby closures.
To understand the method, we need to understand the data type of the argument. The argument is any Ruby object that can be returned by JSON.parse passed a valid JSON string.
The keys are always strings and the values may be strings, numbers, arrays, objects, or null. It is easy to see how JSON.parse parses each into Ruby objects with irb:
The Ruby object returned by JSON.parse is an array or hash with values that can be arrays and hashes that also have values that can be arrays and hashes and so on recursively. The solution is straightforward after appreciating the data type:
Sidebar on closures: prefixing the last parameter of the method with & converts the block argument to that method into a Proc object inside, referenced by that parameter. Prefixing the argument passed into the method with & converts the Proc object to a block argument.
And that’s pretty much it. The following shows some simple uses:
Mileage may vary when it comes to performance. I imagine this could overflow the call stack with a large enough JSON object, for example. Hope this helps!