Skip to content

Instantly share code, notes, and snippets.

@doublec
Created October 24, 2013 06:10
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save doublec/7132119 to your computer and use it in GitHub Desktop.
Save doublec/7132119 to your computer and use it in GitHub Desktop.
JSON parser in Self using the mango parser library
( |
"_" parent* = traits oddball.
object = (| eval = ( |dict = dictionary copy|
members elements do: [|:v. :k|
dict at: v string eval Put: v value eval
].
dict
)
|).
array = (| eval = ( elements elements copyMappedBy: [|:v. :k| v eval] ) |).
float = (| eval = ( source asFloat ) |).
int = (| eval = ( source asInteger ) |).
string = (| eval = ( source copyFrom: 1 UpTo: source size - 1 ) |).
true = (| eval = true |).
false = (| eval = false |).
null = (| eval = nil |).
| )
(*
A basic JSON parser in Self using the mango parser system.
Example run (Assumes files are in a json subdirectory):
|grm. exp|
grm: mango parsers stGrammerParser copy.
grm parseFile: 'json/json.grm'.
exp: grm output makeParser.
exp parseString: '{\"a\":1,\"b\":2}'.
exp output eval (* a dictionary with 'a' and 'b' *)
exp parseString: '[1,2,3.45]'.
exp output eval (* an array with 1,2,3.45 *)
*)
Name: 'json'
Behavior: 'json/json.behavior.self'
Syntax: SLR(1)
Transformations: 'elimEpsilons', 'elimSingletons' ;
<value> ::| <number> {string} <array> <object> {true} {false} {null} ;
<array> ::= '[' <elements> ']' ;
<elements> ::* <value> ',' ;
<object> ::= '{' <members> '}' ;
<members> ::* <pair> ',' ;
<pair> ::= {string} ':' <value> ;
<number> ::| {int} {float} ;
Lex: SLR(1)
Transformations: 'elimEpsilons', 'elimSingletons', 'useCharClasses' ;
{whitespace} -> [ \t\n]+ ;
{float} -> {int} '.' ({digits})? ([eE][+-]? {digits})? ;
{int} -> '-'? {digits} ;
{digits} = [0-9]+ ;
{string} -> '"' [^"]* '"' ;
{true} -> 'true' ;
{false} -> 'false' ;
{null} -> 'null' ;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment