Reputation: 2940
I want to validate JSON with a schema. hjsonschema seemed like a good choice as it is fairly new and supports the latest draft. But the plotly json schema always gives me valid responses.
I may be misunderstanding something here but this should not be valid JSON
bad.json
{
"fjsdklj" : 5
}
even though it is considered valid by the following code
module Main where
import Control.Applicative
import Data.Aeson
import Data.HashMap.Strict (HashMap)
import qualified Data.HashMap.Strict as H
import Data.Monoid
import qualified Data.ByteString.Lazy as B
import qualified Data.JsonSchema as JS
import Data.Maybe
main :: IO ()
main = do
schemaJSON <- (fromJust . decode) <$> B.readFile "simple-schema.json"
bad <- (fromJust . decode) <$> B.readFile "bad.json"
let schemaData = JS.RawSchema {
JS._rsURI = Nothing,
JS._rsData = schemaJSON
}
schema <- compileSchema (JS.SchemaGraph schemaData H.empty) schemaData
checkResults (JS.validate schema bad)
compileSchema :: JS.SchemaGraph -> JS.RawSchema -> IO (JS.Schema JS.Draft4Failure)
compileSchema graph rs =
case JS.compileDraft4 graph rs of
Left failure -> error $ "Not a valid schema: " <> show failure
Right schema -> return schema
checkResults :: [JS.ValidationFailure JS.Draft4Failure] -> IO ()
checkResults [] = putStrLn "Just fine"
checkResults x = putStrLn $ "ERROR: " ++ show x
simple-schema.json
is the plotly schema and bad.json
the snippet I posted above.
Upvotes: 2
Views: 776
Reputation: 3080
It's nothing about Haskell.
Your schema doesn't have a required
property at top level so an empty json object is acceptable.
Also it contains no "additionalProperties": false
property so anything that does not fit into one of the defined patterns are ignored.
BTW I doubt whether it's a valid Draft4 json schema. It passed the validation of the Draft4 meta-schema but the syntax is a little bit different, maybe something Python-specific. You'd better run the test suites which came along with the hjsonscheme
package to see if everything works fine.
Upvotes: 5