Skip to content

Instantly share code, notes, and snippets.

@whostolebenfrog
Forked from ahjones/jsonparse.hs
Created April 25, 2012 17:28
Show Gist options
  • Save whostolebenfrog/2491484 to your computer and use it in GitHub Desktop.
Save whostolebenfrog/2491484 to your computer and use it in GitHub Desktop.
module Parser where
data Token = Open_object | Close_object | Open_array | Close_array | List_delim |
Assign_delim | Quote | String_literal String deriving (Show, Eq, Read)
data JsonElement = FullJsonArray [JsonElement] | StringValue String deriving (Show, Eq, Read)
tokens :: [(Char, Token)]
tokens = [
('{', Open_object),
('}', Close_object),
('[', Open_array),
(']', Close_array),
(',', List_delim),
(':', Assign_delim),
('"', Quote)
]
token_list = map fst tokens
object_sample = "{\"var\": \"val\"}"
array_sample = "[\"x1\", \"x2\", [\"a1\"] ]"
tokenize :: String -> [Token]
tokenize "" = []
tokenize (' ' : rest) = tokenize rest
tokenize (a : rest) = let token = lookup a tokens
predicate x = x /= '"' in
case token of
Nothing -> (String_literal $ takeWhile predicate (a:rest)) :
tokenize (dropWhile predicate (a:rest))
Just t -> t : tokenize rest
parse :: [Token] -> [JsonElement]
parse [] = []
parse (Quote : String_literal lit : Quote : List_delim : rest) = StringValue lit : parse rest
parse (Quote : String_literal lit : Quote : []) = [StringValue lit]
parse list | (head list == Open_array) || (last list == Close_array) =
[FullJsonArray $ (parse . init . tail) list]
main = do
print "hello json"
print ((parse . tokenize) array_sample)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment