Skip to content

Instantly share code, notes, and snippets.

@iArnold
Forked from rebolek/JSON.red
Created October 6, 2016 19:46
Show Gist options
  • Save iArnold/4815ae78499330fc7a5b12eed697a6e5 to your computer and use it in GitHub Desktop.
Save iArnold/4815ae78499330fc7a5b12eed697a6e5 to your computer and use it in GitHub Desktop.
JSON toy parser for Red
Red [
Title: "JSON parser"
File: %json.red
Author: "Nenad Rakocevic"
License: "BSD-3 - https://github.com/red/red/blob/master/BSD-3-License.txt"
]
json: context [
quoted-char: charset {"\/bfnrt}
exponent: charset "eE"
sign: charset "+-"
digit-nz: charset "123456789"
digit: append copy digit-nz #"0"
hexa: union digit charset "ABCDEabcde"
blank: charset " ^(09)^(0A)^(0D)"
ws: [any blank]
dbl-quote: #"^""
s: e: none
data: copy []
decode-str: func [start end /local new rule s][
new: copy/part start back end ;-- exclude ending quote
rule: [
any [
s: remove #"\" [
#"b" (s/1: #"^H")
| #"f" (s/1: #"^(0C)")
| #"n" (s/1: #"^/")
| #"r" (s/1: #"^M")
| #"t" (s/1: #"^-")
| #"u" 4 hexa
]
| skip
]
]
parse new rule
new
]
value: [
string keep (decode-str s e)
| number keep (load copy/part s e)
| "true" keep (true)
| "false" keep (false)
| "null" keep (none)
| object-rule
| array
]
match-value: [
string | number | "true" | "false" | "null" | object-rule | array
]
number: [s: opt #"-" some digit opt [dot some digit opt [exponent sign 1 3 digit]] e:]
string: [dbl-quote s: any [#"\" [quoted-char | #"u" 4 hexa] | dbl-quote break | skip] e:]
couple: [ws string keep (load decode-str s e) ws #":" ws value]
object-rule: [
#"{" collect set list opt [any [couple #","] couple] ws #"}"
keep (make map! list)
]
array: [#"[" collect opt [any [ahead [ws match-value #","] ws value #","] ws value] ws #"]"]
decode: function [data [string!] return: [block! object!]][
parse data [collect any [blank | object-rule | array]]
]
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment