Extract expandObject and expandArray functions.
Namespace internal utility functions.
Add test and logic for invalid input handling.