Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- app "parse-json"
- packages { pf: "platform/main.roc" }
- imports [
- Parser.Core.{ Parser, parse, map, apply, const, buildPrimitiveParser, Result, oneOf,
- parsePartial, ignore, between, many, flatten, oneOrMore, maybe, sepBy1, oneOrMore },
- Parser.Str.{ string, stringRaw, RawStr, strToRaw, parseStrPartial, anyString, codeunit,
- codeunitSatisfies, strFromRaw, digits, digit, parseRawStr }
- ]
- provides [main] to pf
- Value : [
- Null,
- JsonBool Bool,
- JsonNumber I64,
- JsonString Str,
- # JsonArray List Value,
- # JsonObject Dict [Str, JsonValue] ,
- ]
- nullP : Parser RawStr Value
- nullP = string "null" |> map (\_ -> Null)
- trueP : Parser RawStr Value
- trueP = string "true" |> map (\_ -> JsonBool Bool.true)
- falseP : Parser RawStr Value
- falseP = string "false" |> map (\_ -> JsonBool Bool.false)
- dquoteIgnore = ignore (codeunit 34) # '"'
- notDquote = many (codeunitSatisfies (\c -> c != 34)) |> map strFromRaw
- dquotedStrP : Parser RawStr Value
- dquotedStrP = between notDquote dquoteIgnore dquoteIgnore |> map (\s -> JsonString s)
- minus = codeunit 45 # '-'
- maybeMinus = maybe minus
- |> map \res ->
- when res is
- Ok _ -> [45u8]
- Err _ -> []
- manyDigitsP =
- sepBy1 maybeMinus (oneOrMore (codeunitSatisfies (\c -> 48 <= c && c <= 59 )))
- u64P : Parser RawStr Value
- u64P =
- manyDigitsP
- |> map \rawStrs ->
- rawStr = List.join rawStrs
- str = strFromRaw rawStr
- when Str.toI64 str is
- Ok num -> Ok (JsonNumber num)
- Err _ -> Err "`\(str)` is not a I64"
- |> flatten
- # comma = codeunit 44 # ','
- valueP : Parser RawStr Value
- valueP = oneOf [nullP, trueP, falseP, dquotedStrP, u64P]
- iinput: Str
- iinput = "-123"
- # iinput = "\"null\""
- main: Str
- main = parseStrPartial valueP iinput |> (\val ->
- when val is
- Ok parseResult ->
- when parseResult.val is
- Null -> "Null"
- JsonBool tf -> if tf then "True" else "False"
- JsonString s -> "string \(s)"
- JsonNumber n -> (
- s = Num.toStr n
- "number \(s)")
- Err e ->
- when e is
- ParsingFailure s -> "parsing failire: \(s)")
Advertisement
Add Comment
Please, Sign In to add comment