Guest User

parse-json.roc

a guest
Oct 5th, 2022
36
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. app "parse-json"
  2.     packages { pf: "platform/main.roc" }
  3.     imports [
  4.         Parser.Core.{ Parser, parse, map, apply, const, buildPrimitiveParser, Result, oneOf,
  5.             parsePartial, ignore, between, many, flatten, oneOrMore, maybe, sepBy1, oneOrMore },
  6.         Parser.Str.{ string, stringRaw, RawStr, strToRaw, parseStrPartial, anyString, codeunit,
  7.             codeunitSatisfies, strFromRaw, digits, digit, parseRawStr }
  8.     ]
  9.     provides [main] to pf
  10.  
  11. Value : [
  12.     Null,
  13.     JsonBool Bool,
  14.     JsonNumber I64,
  15.     JsonString Str,
  16.     # JsonArray List Value,
  17.     # JsonObject Dict [Str, JsonValue] ,
  18. ]
  19.  
  20. nullP : Parser RawStr Value
  21. nullP = string "null" |> map (\_ -> Null)
  22.  
  23. trueP : Parser RawStr Value
  24. trueP = string "true" |> map (\_ -> JsonBool Bool.true)
  25.  
  26. falseP : Parser RawStr Value
  27. falseP = string "false" |> map (\_ -> JsonBool Bool.false)
  28.  
  29. dquoteIgnore =  ignore (codeunit 34) # '"'
  30. notDquote = many (codeunitSatisfies (\c -> c != 34)) |> map strFromRaw
  31.  
  32. dquotedStrP : Parser RawStr Value
  33. dquotedStrP = between notDquote dquoteIgnore dquoteIgnore |> map (\s -> JsonString s)
  34.  
  35. minus = codeunit 45 # '-'
  36. maybeMinus = maybe minus
  37.     |> map \res ->
  38.         when res is
  39.             Ok _ -> [45u8]
  40.             Err _ -> []
  41.  
  42. manyDigitsP =
  43.     sepBy1 maybeMinus (oneOrMore (codeunitSatisfies (\c -> 48 <= c && c <= 59 )))
  44.  
  45. u64P : Parser RawStr Value
  46. u64P =
  47.     manyDigitsP
  48.     |> map \rawStrs ->
  49.         rawStr = List.join rawStrs
  50.         str = strFromRaw rawStr
  51.        
  52.         when Str.toI64 str is
  53.             Ok num -> Ok (JsonNumber num)
  54.             Err _ -> Err "`\(str)` is not a I64"
  55.     |> flatten
  56.  
  57. # comma = codeunit 44 # ','
  58.  
  59. valueP : Parser RawStr Value
  60. valueP = oneOf [nullP, trueP, falseP, dquotedStrP, u64P]
  61.  
  62. iinput: Str
  63. iinput = "-123"
  64. # iinput = "\"null\""
  65.  
  66. main: Str
  67. main = parseStrPartial valueP iinput |> (\val ->
  68.   when val is
  69.     Ok parseResult ->
  70.       when parseResult.val is
  71.         Null -> "Null"
  72.         JsonBool tf -> if tf then "True" else "False"
  73.         JsonString s -> "string \(s)"
  74.         JsonNumber n -> (
  75.             s = Num.toStr n
  76.             "number \(s)")
  77.     Err e ->
  78.       when e is
  79.         ParsingFailure s -> "parsing failire: \(s)")
Advertisement
Add Comment
Please, Sign In to add comment