1 import Base 2 import ../json.bend as Json 3 import bend-toon-codec@0.1.0.0/main.bend as Toon 4 5 # TOON (spec v3.3) for the JSON data model, through the bend-toon package 6 # published on BendHub as bend-toon-codec (https://github.com/davidawad/bend-toon). 7 # bend-toon declares its own Json type with this module's constructors, so the 8 # two are converted constructor for constructor. 9 10 def to_toon(j: Json.Json) -> Toon.Json: 11 match j: 12 case Json.JNull{}: 13 Toon.JNull{} 14 case Json.JBool{b}: 15 Toon.JBool{b} 16 case Json.JNum{t}: 17 Toon.JNum{t} 18 case Json.JStr{s}: 19 Toon.JStr{s} 20 case Json.JArr{x}: 21 Toon.JArr{to_toon(x)} 22 case Json.JObj{x}: 23 Toon.JObj{to_toon(x)} 24 case Json.JNil{}: 25 Toon.JNil{} 26 case Json.JCons{h, t}: 27 Toon.JCons{to_toon(h), to_toon(t)} 28 case Json.JField{k, v, t}: 29 Toon.JField{k, to_toon(v), to_toon(t)} 30 31 def of_toon(j: Toon.Json) -> Json.Json: 32 match j: 33 case Toon.JNull{}: 34 Json.JNull{} 35 case Toon.JBool{b}: 36 Json.JBool{b} 37 case Toon.JNum{t}: 38 Json.JNum{t} 39 case Toon.JStr{s}: 40 Json.JStr{s} 41 case Toon.JArr{x}: 42 Json.JArr{of_toon(x)} 43 case Toon.JObj{x}: 44 Json.JObj{of_toon(x)} 45 case Toon.JNil{}: 46 Json.JNil{} 47 case Toon.JCons{h, t}: 48 Json.JCons{of_toon(h), of_toon(t)} 49 case Toon.JField{k, v, t}: 50 Json.JField{k, of_toon(v), of_toon(t)} 51 52 # TOON text (indent 2, comma delimiter, LF, no trailing newline). 53 def emit(j: Json.Json) -> String: 54 Toon.encode(to_toon(j), Toon.encode_default()) 55 56 def lift(r: Result<&2, &2, String, Toon.Json>) -> Result<&2, &2, String, Json.Json>: 57 match r: 58 case Done{v}: 59 Done{of_toon(v)} 60 case Fail{e}: 61 Fail{e} 62 63 # The value of TOON text (strict mode); `Fail` starts with the line number. 64 def parse(s: String) -> Result<&2, &2, String, Json.Json>: 65 lift(Toon.decode(s, Toon.decode_default()))