Crockfords JSON 解析器如何工作?
我盯着在这里找到的代码看了很长时间。它是 Douglas Crockfords JSON 解析函数(称为递归下降解析器)。谁能详细说明这个解析器的机制吗?我真的无法理解它。
I have stared for a long time at the code found here. It's Douglas Crockfords JSON-parsing function (called a recursive descent parser). Can anyone elaborate on the mechanics of this parser? I really can't get my head around it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从逻辑上讲,您可以从第 311 行开始的实际解析函数开始(为了清楚起见,省略了接收器部分)。
使用源文本初始化函数全局变量
text
,使用位置初始化位置at
,使用空格初始化当前字符ch
。然后它通过调用函数value
来解析一个值。每个要解析的对象都封装在函数本身中(在上面的示例中是值对象)。其中有几个:
数字
、字符串
、白色
,...)。每个都基本上以相同的方式工作。首先,我们将把white
作为基本示例:请注意,
ch
始终包含当前字符。该变量仅由读取下一个变量的next
更新。这可以在white
中看到,其中每个空白都被对next
的调用所占用。因此,调用此函数后,第一个非空格字符将位于变量ch
中。让我们看一个更复杂的示例
value
:它首先通过调用
white
来解析空格。请注意,ch
现在包含要解析的当前字符。如果它是'{'
,我们现在将看到接下来是一个 json 对象,并调用相应的函数object
。如果它是'['
我们期望一个 json 数组等等。所有其他函数都以相同的方式构建:检查当前字符,决定接下来要做什么,然后解析该对象。
对象本身可能包含其他值,因此您会再次在
object
中发现函数value
的间接递归调用。因此,通过递归调用所有 json 对象函数,它们实际上是从源字符串中解析出来的。Logically you may start with the actual parse functions which starts at line 311 (omitted the receiver part for clarity).
Initializes function global variables
text
with the source text, positionat
with position and current characterch
with a space. Afterwards it parses a value by calling functionvalue
.Each object to be parsed is encapsulated in a function itself (in above example the value object). There are several of them:
number
,string
,white
, ...). Each one does basically work in the same way. First we'll look intowhite
as basic example:Note that
ch
constains always the current character. This variable is only updated bynext
which reads in the next one. This can be seen withinwhite
where each whitespace is eaten by a call tonext
. Thus after calling this function the first non-space character will be in variablech
.Let's look for a more complex example
value
:It first parses whitespaces by calling
white
. Note thatch
now contains the current character to be parsed. If it is a'{'
we'll now that a json object is coming next and call the corresponding functionobject
. If instead it is a'['
we expect an json array and so on.All other functions are build the same way: inspect the current character, decide what has to come next and then parse this object.
The object itself may contain other values and therefore you'll find an indirect recursive call of function
value
inobject
again. Thus by recursively calling all the json object functions they are actually parsed from the source string.