Today I had cause to implement a method for finding and replacing a value that appears at the end of a certain JSON path in an object graph. I couldn't find a preexisting tool to the dirty work so I wrote it myself and then this article. :)
Here's a concrete example. Imagine you have the following JSON:
Now imagine that you want to make the shirt color of every employee with a status of awesome orange. Why? No clue. Work with me here. How would you accomplish that?
After looking for someone else having already done this, I set out to do it myself and was surprised at how simple this was in Ruby. The technique I thought of was to search through every node in the object graph and call a special replace function on each one. If the given node matched the criteria, then it or its children would be updated accordingly.
The following code amounts to a depth first search of the object graph
Really all of the "magic" is in the search method which really just knows how to enumerate either a Hash or an Array, call the replace method and then recursively search its children. If the child object fails some aspect of the replace criteria, nothing happens, we just move on searching through all of its children's Hash or Array children and so on until no other options exist.
What's most surprising to me is the simplicity and elegance of the solution. I probably spent more time looking for an alternate than it took me to write that code.
Now before you think that this will only work in the simplest of cases, here is the actual replacement code I needed for my real world scenario: