是否可以在不使用递归的情况下编写 JSON 解析器?
是否可以在不使用递归的情况下编写 JSON 解析器?如果是,您建议采取什么方法?
Is it possible to write JSON parser without using recursion ? If it is, what approach would you suggest ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
可以使用等效的迭代实现来重现任何递归代码。
这个问题很好地描述了这一点: Is it possible to remove recursion from这个功能?
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?
我同意詹姆斯 - 理论上任何递归代码都可以使用迭代方法来实现。引用的链接上描述的堆栈方法是一个有效的选项。另一种方法是,您可以硬编码到
n
深度,但显然存在被限制在所述深度的风险。如果不了解您尝试运行 JSON 处理代码的环境和约束,就很难说哪种方法最适合。需要考虑的一些事情:
n
深度场景n
深度场景,但可能不那么直观对于其他程序员来说,还可以线性化树结构(JSON 的对象图是隐式的,假设 array-only 可以有一个“array”的虚拟根)。这允许采用平流处理方法。如果您更进一步并注入诸如
DOWN
和UP
之类的人工标记,它可能会变得非常易读。这是编译器设计和语言分析中出现的内容,但作为一个概念在这里可能会有所帮助。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
andUP
it can be highly legible. This is something which comes up in compiler design and language analysis, but maybe helpful as a concept here.