Skip to content

Instantly share code, notes, and snippets.

@osfameron
Created September 1, 2020 09:44
Show Gist options
  • Save osfameron/19498d2edc69785a88825694e6427e3b to your computer and use it in GitHub Desktop.
Save osfameron/19498d2edc69785a88825694e6427e3b to your computer and use it in GitHub Desktop.
Simpler passthrough of un-codec'd fields
module JsonTest where
import Prelude (bind, pure, ($), (<<<))
import Data.Argonaut.Core (Json, fromObject, stringify, toObject)
import Data.Argonaut.Decode (JsonDecodeError(..), decodeJson, parseJson)
import Data.Argonaut.Encode (encodeJson)
import Data.Either (Either, note)
import Foreign.Object as O
import Data.Tuple (Tuple(..))
import Data.Maybe (Maybe, fromJust)
import Partial.Unsafe (unsafePartial)
type Foo = { foo :: String, bar :: Number, _json :: Json }
decodeFoo :: Json -> Either JsonDecodeError Foo
decodeFoo = decodeJson
j :: String
j = """{"foo":"Hello","bar":1.0,"baz":"extra"}"""
process :: String -> Either JsonDecodeError String
process json =
do
parsed <- parseJsonWithPassthrough json
decoded <- decodeFoo parsed
let updated = decoded { foo = "Updated", bar = 2.0 }
let encoded = encodeJson updated
pure $ unsafeStringifyWithPassthrough encoded
parseJsonWithPassthrough :: String -> Either JsonDecodeError Json
parseJsonWithPassthrough s = do
json <- parseJson s
obj <- note (TypeMismatch "Not an object") $ toObject json
let obj' = O.insert "_json" json obj
pure $ fromObject obj'
stringifyWithPassthrough :: Json -> Maybe String
stringifyWithPassthrough json = do
obj <- toObject json
(Tuple json' obj') <- O.pop "_json" obj
orig <- toObject json'
let merged = O.union obj' orig
pure $ stringify (fromObject merged)
unsafeStringifyWithPassthrough :: Json -> String
unsafeStringifyWithPassthrough = unsafePartial fromJust <<< stringifyWithPassthrough
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment