Is it possible to write JSON parser without using recursion ? If it is, what approach would you suggest ?
Its possible to reproduce any recursive code with an equivalent iterative implementation.
This question describes this quite nicely: Is it possible to remove recursion from this function?
I agree with James - any recursive code can theoretically be implemented using an iterative approach. The stack method described on the referred link is a valid option. The alternative is that you can hard-code to n
depth, with the obvious risk of then being limited to said depth.
Without knowing more about the environment and constraints under which you are trying to run your JSON handling code, it's difficult to say which approach is the best fit. Some things to consider:
n
-depth scenariosn
-depth scenarios, but may not be as intuitive to other programmersAlso, it is possible to linear-ize a tree structure (which the object graph of a JSON is implicitly, assuming array-only can have a virtual root of "array"). This allows a flat-stream processing approach. If you go a step further and inject artificial tokens such as DOWN
and UP
it can be highly legible. This is something which comes up in compiler design and language analysis, but maybe helpful as a concept here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With