爲了紀念Rebol 3開放源代碼any-minute-now (?),我又回到了搞亂它。作爲練習,我試圖用PARSE方言編寫自己的JSON解析器。PARSE方言應該用於基本上關於修改輸入的任務嗎?
既然道格拉斯克羅克福德credits influence of Rebol on his discovery of JSON,我認爲這很容易。除了使用方括號替換大括號並擺脫所有這些逗號之外,僅在字符串上使用LOAD
的障礙之一是,當他們想要做相當於SET-WORD!
的事實時,他們使用的東西看起來像字符串給Rebol的標記器與後非法流浪冒號:
{
"key one": {
"summary": "This is the string content for key one's summary",
"value": 7
},
"key two": {
"summary": "Another actually string, not supposed to be a 'symbol'",
"value": 100
}
}
基本上,我想找到所有的都像"foo bar":
的情況下,把它們變成foo-bar:
,同時留下了後面沒有冒號單靠匹配報價對。
當我在PARSE中解決這個問題時(我原則上理解的很好,但仍未使用太多),出現了一些問題。但是,主要的是,當你可以逃避代碼並修改解析器下的系列時(特別是在Rebol 3中),有什麼承諾條件?更一般地說,它是「適合這種工作的工具」?
這裏是我試過的規則,這似乎爲任務的這部分工作:
any [
; require a matched pair of quotes & capture series positions before
; and after the first quote, and before the last quote
to {"} beforePos: skip startPos: to {"} endPos: skip
; optional colon next (if not there the rest of the next rule is skipped)
opt [
{:}
; if we got to this part of the optional match rule, there was a colon.
; we escape to code changing spaces to dashes in the range we captured
(
setWordString: copy/part startPos endPos
replace/all setWordString space "-"
change startPos setWordString
)
; break back out into the parse dialect, and instead of changing the
; series length out from under the parser we jump it back to the position
; before that first quote that we saw
:beforePos
; Now do the removals through a match rule. We know they are there and
; this will not cause this "colon-case" match rule to fail...because we
; saw those two quotes on the first time through!
remove [{"}] to {"} remove [{"}]
]
]
這樣行不行?在開放代碼中是否有機會詆譭外部解析......如果不是在這種情況下,那麼在一些細微的不同之處呢?
一如既往,任何教誨「它更乾淨/更短/更好的這種方式」建議表示讚賞。
P.S.爲什麼沒有replace/all/part
?
這不是你要求的,但是如果你還沒有這樣的代碼,請檢查這段代碼:http://reb4.me/r/altjson REBOL <-> Christopher Ross-Gill的JSON轉換器。 – endo64